【问题标题】:Why is 0 appearing in my code while working with text files [duplicate]为什么在处理文本文件时我的代码中出现 0 [重复]
【发布时间】:2016-01-20 19:13:44
【问题描述】:

我有一个文本文件,里面是:

3
7 8 9 7 8
5 7 9 5 7
6 8 7 9 7

我已将 3 设置为 int 'd'。所有其他行都应该属于 int 'b'。但似乎'b'仍然计入第一行,将其提取到'd'后变为0。

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    int b, d;
    string line;
    ifstream file("File.txt");

    if(!file.is_open())
        cout << "File failed to open." << endl;

    file >> d;

    while(getline(file, line))
    {
        istringstream iss(line);
        double v = 0;

        while(iss >> b)
            v += b;

        cout << v / 5 << endl;
    }

    return 0;
}

它输出:

0
7.8
6.6
7.4

我能做些什么来解决这个问题?提前谢谢你:)

【问题讨论】:

    标签: c++ file text int output


    【解决方案1】:

    之后

    file >> d;
    

    换行符仍在输入流中。第一次调用getline 返回一个空行。

    使用

    file >> d;
    
    // Ignore the rest of the first line.
    file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
    while(getline(file,line))
    

    并确保添加

    #include <limits>
    

    能够使用std:numeric_limits。

    【讨论】:

    • #include for numeric_limits
    【解决方案2】:

    这是因为您在使用operator&gt;&gt; 阅读后使用了std::getline,它在提取完成后不会消耗空格字符(包括换行符)。

    所以,换行符仍然存在,您的第一个 std::getline 一直读取到该字符(在您的情况下没有任何内容 - iss 为空)并且提取 iss &gt;&gt; b 失败,因此 v 不会增加。做

    file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    

    在file &gt;&gt; d; 之后使用换行符并在下一行继续阅读。

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 2013-04-07
      相关资源
      最近更新 更多