【发布时间】:2020-08-14 02:04:41
【问题描述】:
我有包含此信息的 file1.txt
4231650|A|4444
4225642|A|5555
我在这里查看了如何在 C++ 中读取管道分隔文件的代码
C++ Read file line by line then split each line using the delimiter
我根据需要稍微修改了代码。问题是它可以很好地读取第一个管道,但之后我如何读取其余的值?
这是我的代码:
std::ifstream file("file1.txt");
std::string line;
while(std::getline(file, line))
{
std::stringstream linestream(line);
std::string data;
std::string valStr1;
std::string valStr2;
std::getline(linestream, data, '|'); // read up-to the first pipe
// Read rest of the pipe values? Why did the accepted answer worked for int but not string???
linestream >> valStr1 >> valStr2;
cout << "data: " << data << endl;
cout << "valStr1: " << valStr1 << endl;
cout << "valStr2: " << valStr2 << endl;
}
这是输出:
Code Logic starts here ...
data: 4231650
valStr1: A|4444
valStr2: A|4444
data: 4225642
valStr1: A|5555
valStr2: A|5555
Existing ...
【问题讨论】:
-
您没有代码可以读取到第二个管道!您也不会检查您的读取是否成功。
-
@DavidSchwartz 我复制并粘贴了上一篇文章中接受的答案。并将其用于字符串而不是 int
-
@SamB 切勿将他人的代码剪切/粘贴到您的代码中,除非您理解并亲自确认它适用于您的问题。
-
这不是“它与
int合作”。它是“它与制表符(空格)分隔的值一起使用”。