2

I have a text file with inside made of:

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

I have set 3 to int 'd'. All other lines should belong to int 'b'. But it seems that 'b' still counts in the first line, which became 0 after extracting it to 'd'.

#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;
}

It outputs:

0
7.8
6.6
7.4

What could I do to fix this ? Thank you in advance :)

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Arquon
  • 25
  • 2

2 Answers2

0

It's because you're using std::getline after you've read with operator>>, which doesn't consume whitespace characters (including newline) after the extraction is done.

So, the newline character is still there, your first std::getline reads till that character (in your case nothing - iss is empty) and extraction iss >> b fails, thus v is not incremented. Do

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

after file >> d; to consume the newline character and continue reading on the next line.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
0

After

file >> d;

the newline character is still in the input stream. The first call to getline returns an empty line.

Use

file >> d;

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

while(getline(file,line))

And make sure to add

#include <limits>

to be able to use std:numeric_limits.

R Sahu
  • 204,454
  • 14
  • 159
  • 270