【问题标题】:C++: How to read from specific line in .dat fileC++:如何从 .dat 文件中的特定行读取
【发布时间】:2013-09-22 03:35:10
【问题描述】:

我是 C++ 新手,我正在尝试通过读取每行都是这种形式的 .dat 文件来构造一个指向 Student 类型的指针数组:

101 Jones 92.7 54.3 88 .4*88+.3*(92.7+54.3)

每一行都是结构体的一个实例,并存储在一个指向学生的指针数组中。 这是我的代码:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
const int N = 100;
struct Students{
        int classid;
        string lastname;
        float exam1;
        float exam2;
        float final;
        float score;
};


int main(void){
        Students* s[N];
        ifstream input;
        ofstream output; 
        input.open("examscores.dat");
        for(int i=0; i< 10; i++){
                s[i] = new Students; 
                input >> s[i]->classid >> s[i]->lastname >> s[i]->exam1 >> s[i]->exam2 >> s[i]->final >> s[i]->score;
        }
        cout << s[0]->classid << endl;
        cout << s[4]->classid << endl;
        cout << s[5]->classid << endl;
return 0;
}   

我期望这个输出:

101
105
106

但我明白了:

101
0
0

【问题讨论】:

  • 您是否尝试将您的input &gt;&gt; 提取扩展为单数提取列表,并使用调试器 来确定哪个失败(因此为什么其余的也是DOA)?我相当有信心第一行在提取中失败了,之后流的其余部分都死了,直到你清除失败位。无论如何,这确实应该使用std::getline()std::istringstream 线路处理器来完成。
  • ".dat" 文件没有意义。它是一个文本文件吗?
  • @Rapptz OP 不想转到文件中的特定行。

标签: c++


【解决方案1】:

.4*88+.3*(92.7+54.3) 不适合 float。您必须将其作为字符串读取,然后自己解析表达式。

当您使用input &gt;&gt; ... &gt;&gt; s[i]-&gt;score 时,它会读取.4,但将其余部分 (*88+.3*(92.7+54.3)) 留在缓冲区中并搞砸后续读取。

快速修复:float score; 替换为 std::string score;

【讨论】:

    猜你喜欢
    • 2019-08-25
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多