954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

getline() error when cin is redirected

Dear all,

I experienced an unexpected error when using getline() to get input from a file like this:

a.out < inputFile

Part of the code is shown below

........

while (true) {
    
        cout << "Enter a command: ";
        getline(cin, input);
        
        cout << input << endl;
            
}

.........


The output is:

....
Enter a command: 
Enter a command: 
Enter a command: 
Enter a command: 
Enter a command: 
Enter a command: 
Enter a command: 
Enter a command: 
.....


It fails to get anything from the input file. But it runs without problem if the while loop is removed and enter 'a.out < inputFile'

#include <iostream>
using namespace std;
int main()
{
   cout << "Enter a command: ";
   getline(cin, input);
        
   cout << input << endl;

   return 0;
}


What getline() behaves differently inside and outside a loop?


Jim

jimFan
Newbie Poster
22 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

>while (true) {
You don't break from this loop anywhere. It's going to continue looping forever, after a short time getline will start to fail and you'll get the output you posted. Try this instead:

while ( getline ( cin, input ) )
  cout << input << endl;

At least that way the loop will stop when input is exhausted.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Thanks for that Narue.

Since I have placed several rows of words in the inFile, although the loop goes infinitely it should be able to print the file's content. But this is not the case. It just prompts

Enter a command:
Enter a command:
Enter a command:
Enter a command:
Enter a command:

without a single word from the file.

Jim

jimFan
Newbie Poster
22 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

Let's see both of your test programs in their entirety. You said that one uses a loop and the other doesn't, and that this is the only difference between the two, yet that shouldn't have any effect on whether you get output or not.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

use cin.ignore() before getline function.

p9v9n261
Newbie Poster
1 post since Aug 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You