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

>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.

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

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.

use cin.ignore() before getline function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.