c++ - istringstream 不在变量中存储任何内容

标签 c++ file variables

我遇到一个问题,istringstream 没有存储它读取的值。这是我所拥有的:

      if(inputFile.good()){                                         //Make sure file is open before trying to work with it
                                                                    //Begin Working with information
        cout << "\tIn File:  " << input << endl;
        cout << "------------------------------------" << endl;
        int number_of_lines = 0;
        std::string line;
        while (std::getline(inputFile, line)){
            ++number_of_lines;
        }
        Time times[number_of_lines];
        double math[number_of_lines];
        std::string input;
        int hh, mm;
        for(int loop=0;loop<number_of_lines;loop++){
            std::getline(inputFile, input);
            std::istringstream(input) >> mm >> hh >> math[loop];
            cout << "hours = " << hh << endl;
            times[loop].setTimeHours(hh);
            times[loop].setTimeMinutes(mm);
            times[loop].show();
            cout << "*" << math[loop] << endl;
        }
        std::cout << "Number of lines in text file: " << number_of_lines << "\n" << endl;
    }else{
        cout << "Could not open file!!!" << endl;
    }

我正在阅读的文件如下所示:

90 1 3.0
1 1 100.0
2 34 5.1

以及我运行时的输出:

  In File:  data04.txt
 ------------------------------------
 hours = 0
 Operation To Be Done = 0:2336552*1.15384e-317
 hours = 0
 Operation To Be Done = 0:2336552*1.58101e-322
 hours = 0
 Operation To Be Done = 0:2336552*1.15397e-317
 Number of lines in text file: 3

有人知道为什么它不存储值吗?

最佳答案

这段代码有几个关键问题

  1. 它不检查输入是否成功。您始终需要确保在处理读取的数据之前验证输入操作是否有效。否则将导致处理随机数据。
  2. 您首先阅读到流的末尾,然后希望流神奇地重新启动。那行不通的。只读取一次流并继续附加到 std::vector<Time> (或类似的容器)。除了只遍历文件一次外,在 UNIX 上,文件大小可以在读取时改变。
  3. C++ 没有可变大小数组,尽管某些编译器可能提供类似于 C 的可变大小数组的扩展。在 C++ 中,您将使用 std::vector<Time>相反。

关于c++ - istringstream 不在变量中存储任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20552972/

相关文章:

php - 尝试使用查询变量和表单数据来更改数据库中的表

c++ - 使用 size_type 索引从 std vector 中删除会导致编译器错误?

firebase - 类型 'String' 不是类型 'File' 的子类型

c++ - sizeof 是在编译时还是运行时求值?

python - 如何知道 python 中一行 CSV 文件的字节位置?

file - 如何在Haskell(跨平台)中获取文件访问时间?

python - 如何处理用 Pandas 导入的数据?

python - 在 IPython 中移除或删除变量

c# - glBufferData 总是因 GL_INVALID_ENUM 而失败,即使它不应该

c++ - 如何在 C++ 的 main 中使用 struct 的数组数据成员?