0

Why does getline() reads only the first line multiple times ? I also tried using getline() within the while loop but it gives the same result.Any specific reason why this is happening ?

void closestPair(char inFile[50],char outFile[50])
{
    int num1,num2;
    int i =0;
    string line ="";
    stringstream ss;
    ifstream fp(inFile);    
    while(!fp.eof())
    {
        getline(fp,line);
        ss<<line;
        ss>>num1>>num2;
        A[i].x = num1;
        A[i].y = num2;
        i++;
        printf(" %d %d \n", num1, num2);
    }
fp.close();
} 

my input file:

1 3

4 6

7 9

8 5

2 5

output: 1 3 1 3 1 3 1 3 1 3

Syed
  • 57
  • 1
  • 6
  • 1
    My guess would be, `ss` reaches end-of-file state after `ss>>num1>>num2;` runs for the first time. Once the `eof` bit is set, all subsequent calls are failing on that stream, and so `num1` and `num2` keep their original values. `getline` most likely works fine (to check that, print `line`). – Igor Tandetnik Sep 20 '19 at 04:15
  • I tried printing the " line ", it gave same results – Syed Sep 20 '19 at 04:15
  • [Works for me](https://rextester.com/JDPE93412), in that `line` is read correctly. It's extracting the two numbers from `line` that fails. – Igor Tandetnik Sep 20 '19 at 04:19
  • Yeah worked fine, but values in the struct array A are not stored properly, it stores all zeros – Syed Sep 20 '19 at 04:24

1 Answers1

0

I would suggest changing the scope of ss to see predictable results.

void closestPair(char inFile[50],char outFile[50])
{
    int num1,num2;
    int i =0;
    string line ="";
    ifstream fp(inFile);    
    while( getline(fp, line) )
    {
        stringstream ss;  // Move it inside the loop.
        ss<<line;
        ss>>num1>>num2;
        A[i].x = num1;
        A[i].y = num2;
        i++;
        printf(" %d %d \n", num1, num2);
    }
    fp.close();
} 

Better still, construct a std::ostringstream from line and use it to extract the numbers.

void closestPair(char inFile[50],char outFile[50])
{
    int num1,num2;
    int i =0;
    string line ="";
    ifstream fp(inFile);    
    while( getline(fp, line) )
    {
        std::ostringstream ss(line);
        ss>>num1>>num2;
        A[i].x = num1;
        A[i].y = num2;
        i++;
        printf(" %d %d \n", num1, num2);
    }
    fp.close();
} 

See Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong? regarding while(!fp.eof()).

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