1

我正在尝试做的是在使用 sstream 库进行解析时从每行的文本文件中读取。我让程序运行,但它卡在一个循环中。

程序:

string date;
int time;
float amount;

ifstream testFile("test.txt");
string token;
string line;

while(!testFile.eof()) {

    while(getline(testFile,token,',')){
        line += token + ' ';
    }
    stringstream ss(line); 
    ss >> date;
    ss >> time;
    ss >> amount;

    cout << "Date: " << date << " ";
    cout << "Time: " << time << " ";
    cout << "Amount: " << amount << " ";
    cout<<endl;

    ss.clear();

}    
testFile.close();

测试.txt:

10/12/1993,0800,7.97
11/12/1993,0800,8.97

想要的输出:

Date: 10/12/1993 Time: 0800 Amount: 7.97
Date: 11/12/1993 Time: 0800 Amount: 8.97

我怎样才能有效地产生这个?

4

2 回答 2

2
  1. 不要循环使用eof. 为什么循环条件内的 iostream::eof 被认为是错误的?

  2. 逐行读取文件。逐行读取文件

  3. ,使用分隔符拆分每行的字符串。在 C++ 中拆分字符串?

  4. 创建std::stringstream第二个和第三个字符串的对象,并operator>>从中获取intdouble值。

于 2017-01-04T04:47:32.630 回答
1
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{    
    ifstream testFile("testdates.txt");    
    string line;

    while(getline(testFile, line)){

        string date;
        int time;
        float amount;

        std::replace(line.begin(), line.end(), ',', ' ');

        stringstream ss(line);

        ss >> date;
        ss >> time;
        ss >> amount;

        cout << "Date: " << date << " ";
        cout << "Time: " << std::setfill('0') << std::setw(4) << time << " ";
        cout << "Amount: " << amount << " ";

        cout << '\n';
    }   
}

您应该使用 . 逐行阅读getline。您应该检查 this 的返回值以了解何时退出(不是!eof)。然后,您可以用空格替换所有逗号,并使用现有的流解析代码来读取值。

注意ss.clear()andtestFile.close()不是必需的,因为ss它在每次迭代中重新创建并testFile在其析构函数中关闭。

于 2017-01-04T04:50:04.287 回答