0

So I'm trying to either

a) allow user to input a string until they type exit

or

b) redirect file from standard input(a.out < test.txt) until at end of file and then terminate

My attempt at the code:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main(){

    string input = "";
    while(true){
       cout << "Enter string: ";
       while(getline(cin, input)){
       if(input == "exit" || cin.eof()) goto end;
       cout << input << "\n";
       cout << "Enter string: ";                       
     }

    }
    end:
    return 0;



}

This causes an issue with redirection, when I use command a.out < test.txt I get an infinite loop (where test.txt contains one line "hello")

User input seems to work fine

I'm using getline because in the actual program I need to read a file line by line and then manipulate the line before moving on to the next line of the file

EDIT: My question is, how do I terminate this loop accounting for both user input and redirection?

1
  • Your code is working for me ideone.com/pj0xID Commented Oct 16, 2015 at 3:06

2 Answers 2

1
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main(){
  string input = "";
  while(cin && cout<<"Enter string: " && getline(cin, input)){
    //check both cout and cin are OK with the side effect of
    // writing "Enter string" and reading a line

    if(input == "exit") return 0; //no need for a goto
    cout << input << "\n";
  }
  if(cin.eof()) return 0; //ended because of EOF
  return 1; //otherwise, the loop must have broken because of an error
}

Keep it simple. You don't need the outer loop and the cin.eof() will never be true inside the while block because if cin.eof() is true, then the getline expression which returns cin which converts to bool would convert to false, thereby ending the loop.

The loop ends if cin encounters the EOF or an error.

Sign up to request clarification or add additional context in comments.

Comments

1

well, in first case use of goto is not recommended, you can use boolean data type to achieve your goal:

int main(){
bool flag = true;

string input = "";
while(flag){
    cout << "Enter string: ";
    while(getline(cin, input)){
        if(input == "exit" || cin.eof()) {
            flag = false;
            break;
        }
        cout << input << "\n";
        cout << "Enter string: ";
    }

  }


 return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.