C ++ - 从文件读取到双倍

时间:2013-11-10 03:16:10

标签: c++ readfile

我目前在编程和学习C ++课程方面比较陌生。到目前为止我没有遇到任何重大问题。我正在制作一个程序,其中X金额法官可以得分0.0 - 10.0(双倍),然后移除最高和最低一个,然后计算并打印出平均值。

此部分已完成,现在我想从以下形状的文件中读取: example.txt - 10.0 9.5 6.4 3.4 7.5

但是我遇到了点(。)的问题,以及如何绕过它以使数字变为双数。任何建议和(好的)解释,以便我能理解它?


TL; DR:从文件(E.G.'9.7')读取到双变量以放入数组。

2 个答案:

答案 0 :(得分:4)

由于您的文本文件是以空格分隔的,因此您可以利用默认情况下跳过空格的std::istream个对象(在本例中为std::fstream)来利用它: / p>

#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>

int main() {
    std::ifstream ifile("example.txt", std::ios::in);
    std::vector<double> scores;

    //check to see that the file was opened correctly:
    if (!ifile.is_open()) {
        std::cerr << "There was a problem opening the input file!\n";
        exit(1);//exit or do additional error checking
    }

    double num = 0.0;
    //keep storing values from the text file so long as data exists:
    while (ifile >> num) {
        scores.push_back(num);
    }

    //verify that the scores were stored correctly:
    for (int i = 0; i < scores.size(); ++i) {
        std::cout << scores[i] << std::endl;
    }

    return 0;
}

注意:

强烈建议尽可能使用vectors代替动态数组,原因如下所述:

When to use vectors and when to use arrays in C++?

答案 1 :(得分:1)

试试这个:

#include <iostream>
#include <fstream>

int main() 
{
    std::ifstream fin("num.txt");
    double d;
    fin >> d;
    std::cout << d << std::endl;
}

这样做你想要的吗?