Jim JANES
Jim JANES

Reputation: 37

C++, cin until no more input on line using a while loop

I am having an issue with my C++ program. I reformat and display words that a user enters into the console. If a user enters : Hi I am bob.The user will press enter after entering bob into the console. I will reformat this and reprint it in it's new format. The problem is I do not want to display a message for more input until all of the words on that console line is input. The current loop I have either displays the request for input after each word, or does not display it at all. It depends on whether or not I include the prompt or not. I need to make a while loop process each word and output it and stop after the last word. What is a Boolean param for that? I am including my code for reference.

int _tmain(int argc, _TCHAR* argv[])
{

    int b;
    string input;
    string output ;
    int check = 1;

    while (check){
        cout << "Enter in one or more words to be output in ROT13: " << endl;
        cin >> input;
        while(my issue is here){

            const char *word = input.c_str();

            for (int i = 0; i < input.length(); i++){

                b = (int)word[i];
                if (b > 96){
                    if (b >= 110){
                        b = b - 13;
                    }
                    else {
                        b = b + 13;
                    }

                    output += ((char)b);
                }

                else
                {
                    if (b >= 78){
                        b = b - 13;
                    }
                    else {
                        b = b + 13;
                    }

                    output += ((char)b);
                }







            } 
            cout << output << endl;
            output = "";
            cin >> input;

        }

            check = 0;

    }

    return 0;
}

Upvotes: 1

Views: 35559

Answers (2)

user2486888
user2486888

Reputation:

You may replace the entire while loop with this line:

std::getline(std::cin, input);  // where input is a std::string

And then do the reformatting after this line.

Upvotes: 5

Jim Gao
Jim Gao

Reputation: 117

The cin function would return false if there is no more lines for input. You can do the following to read until the end of input, or eof if you are redirecting cin to read from a file.

int a;
while(cin >> a){
    //Your loop body
}

Upvotes: 9

Related Questions