C++ stringstream 读取全零
我有一个文件,每行包含三个整数。当我读取该行时,我使用字符串流来分隔值,但它只按原样读取第一个值。另外两个读作零。
ifstream inputstream(filename.c_str());
if( inputstream.is_open() ){
string line;
stringstream ss;
while( getline(inputstream, line) ){
//check line and extract elements
int id;
double income;
int members;
ss.clear();
ss.str(line);
ss >> id >> income >> members;*emphasized text*
}
}
在上面的例子中,id 被正确提取,但收入和成员被分配为零而不是实际值。
编辑:解决了
没关系。该代码工作正常。错误出现在我的打印语句中。我有一个 for 循环,每次都在同一索引处打印数组。
I have a file which contains three integers per line. When I read the line I use a stringstream to separate the values, but it only reads the first value as it is. The other two are read as zero's.
ifstream inputstream(filename.c_str());
if( inputstream.is_open() ){
string line;
stringstream ss;
while( getline(inputstream, line) ){
//check line and extract elements
int id;
double income;
int members;
ss.clear();
ss.str(line);
ss >> id >> income >> members;*emphasized text*
}
}
In the case above, id is extracted correctly, but income, and members get assigned zero instead of the actual value.
EDIT: Solved
Never mind. The code works correctly. The error was in my print statement. I had a for loop printing the array at the same index every time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不直接从文件中读取呢?
Why don't you read directly from the file?