gpt4 book ai didi

c++ getline和stringstream

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:35 26 4
gpt4 key购买 nike

我正在尝试读取一个文件,该文件有 5 行,每行有 3-4 个字符串长。这是我的输入文件:

10:30 Hurley 1234567A 10:15
10:45 Hurley 1234567A 11:30
08:35 Jacob 1x1x1x1x1x
08:35 Jacob 1x1x1x1x1x 08:10
08:05 Jacob 1x1x1x1x1x
08:45 Sayid 33332222 09:15

这就是我得到的:

10:30 Hurley 1234567A   10:15
10:45 Hurley 1234567A 11:30
08:35 Jacob 1x1x1x1x1x 11:30
08:35 Jacob 1x1x1x1x1x 08:10
08:05 Jacob 1x1x1x1x1x 08:10
08:45 Sayid 33332222 09:15

这是我的代码:

void enor::Read(status &sx,isle &dx,ifstream &x){
string str;
getline(x, str, '\n');
stringstream ss;
ss << str;
ss >> dx.in >> dx.name >> dx.id >> dx.out;
/*getline(x, str, '\n');
x>>dx.in>>dx.name>>dx.id>>dx.out;*/
if(x.fail())
sx=abnorm;
else
sx=norm;
}

如何在第 3 行和第 5 行不填满第 2 行和第 4 行的时间的情况下读取文件?我希望 dx.out 为空。我应该使用另一种方法,还是可以使用 stringstream 来完成?

最佳答案

如果 >> 发现 stringstream 中没有任何内容,它将保持变量不变 - 所以 dx.out 保留它的最后一行的值。但是,你可以这样做

ss >> dx.in >> dx.name >> dx.id;
if (!(ss >> dx.out))
dx.out = "";

因为ss >> dx.out返回ss,而当一个stream被转换成一个bool的时候(比如在使用的时候在 if 条件下),如果最后一次读取尝试失败,则返回 false

关于c++ getline和stringstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com