我想编写一个从文件中读取文本行的程序。每一行包含多个字符串、一个整数和一个 double 值。行数事先未知(即,程序需要读取行直到文件末尾),并且每行的长度也不知道。 while 循环检查该行是否按以下方式排序:
-- string -- integer -- double --- string
Cat. 3: 18.00 Kr. [ Tvål ]
Cat. 1: 14.50 Kr. [ Äppelmos Bob ]
Cat. 1: 12.00 Kr. [ Coca Cola 2 lit. ]
Cat. 1: 18.00 Kr. [ Kroppkakor 4 st. ]
问题是最后一个字符串包含多个空格,因此程序不会将其视为一个完整的字符串。最后一个字符串像几个字符串一样被接受,我在屏幕上只看到 Cat。 3:18.00 Kr。而不是整个线路列表。
我尝试处理这样的程序:
double doubleValue;
int intValue;
string str1, str2, str3;
ifstream infile("Register.txt", ifstream::in);
while (infile >> str1 >> intValue >> str2 >> doubleValue >> str3)
{
cout << intValue << " " << doubleValue << endl;
}
提前致谢。
最佳答案
这是因为operator>>
将在空格处停止解析。
要解决这个问题,您可以先使用 std::getline()
读取整行内容。 。然后,解析前四个部分(通过应用 std::stringstream
),最后通过调用 std::getline()
获取剩余部分。再次。
#include <sstream>
using namespace std;
string line;
while (getline(infile, line)) // read the whole line from the file
{
stringstream ss(line);
ss >> str1 >> intValue >> str2 >> doubleValue; // pause the first four parts
getline(ss, str3); // parse the remaining part to str3, e.g. "Kr. [ Tvål ]"
}
关于c++ - 从也包含字符串的 .txt 文件中读取整数和 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23327141/