C++ stringstream 读取全零

发布于 2024-09-01 08:28:01 字数 588 浏览 13 评论 0原文

我有一个文件,每行包含三个整数。当我读取该行时,我使用字符串流来分隔值,但它只按原样读取第一个值。另外两个读作零。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绿萝 2024-09-08 08:28:01

为什么不直接从文件中读取呢?

while( inputstream ) {
    if( ! inputstream >> id ) ...
    if( ! inputstream >> income ) ...
    if( ! inputstream >> members ) ...
}

Why don't you read directly from the file?

while( inputstream ) {
    if( ! inputstream >> id ) ...
    if( ! inputstream >> income ) ...
    if( ! inputstream >> members ) ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文