Dear all,

Forgive me for posting two threads for the same problem. I was not showing my problem clearly enough in the previous one. Thank Narue for answering that anyway. Now I do it again here:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string inputStr;
    while (true)
    {
        getline(cin, inputStr);
        if (inputStr == "quit") break;
        cout << inputStr << endl;
    }
    return 0;
}

This programme runs fine when I compile and click the executable. But things go wrong if I do it in command-line and redirect the input stream to a text file:

$a.out < inputFile

*The programme does not let me do any input and it loops again and again instead.* I guest this is a problem associated with getline() function.

So what do you think about this?

Jim

Recommended Answers

All 5 Replies

This programme runs fine when I compile and click the executable. But things go wrong if I do it in command-line and redirect the input stream to a text file:

$a.out < inputFile

Don't you mean input from? What are the contents of your input file?

Or do you mean to redirect the output to a file?

$a.out > inputFile

Don't you mean input from? What are the contents of your input file?

Or do you mean to redirect the output to a file?

$a.out > inputFile

Hi Dave,

Oh sorry for my grammer. I actually mean input from:

$a.out < inputFile

Here is what the content of inputFile maybe:

ls
changecc COMP271 5
quiz
quit

The problem occur when the programme has read all the way to the last line:

quit

The programme loops and does not ask me for input.


Jim

can you make an infinite program using do while loop??

commented: I'm not liking this trend of resurrecting dead threads... +0
commented: 2005? -2

try doing getline(inputStr,10,'\n') it should work instead of getline(cin, inputStr)

can you make an infinite program using do while loop??

You can make an infinite loop with any loop structure, it just depends on how you write it...

@OP:
According to this article, getline has a default delimiter of '\n' that it detects and discards. The issue may be that at the end of a line (on Win systems) there is '\r\n'. As a result, I suspect that getline() is picking up 'quit\r' which does not match 'quit'. Try specifying getline(cin, inputStr, '\r') and see what happens. I don't know how this will affect your non-redirected version though.

EDIT:
WTF!!!! Why am I posting in an almost 5-year-dead thread!?!?!? This has got to stop!! :@

commented: Yes, but unfortunately the DW search engine seems to have a preference for anniversaries for some reason. +19
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.