Using return key in while loop


I'm trying to learn programming from a book. In one drill I am expected to use a while loop to ask for and return two integers. To end the loop the user is expected to enter a '|' character. I have a prompt to ask continue or enter the '|' key to end. The program works okay until the enter key is used to indicate whether or not to continue. When enter is pressed, the cursor moves down a line but waits for the '|' key. I tried an if statement to watch for a '\n' and '\r', and I believe is tried '\n' keystrokes, but nothing goes into the char variable controlling the loop. Could I be using the wrong characters for the return key? Is the return character specific to the compiler?

It would be helpful to see your code.
Here it is.

[code/* Program whileloops. This program uses a while loop to take in and print out two integers.
*/
#include <iostream>
using namespace std;

int main()
{

int number1 = 0;
int number2 = 0;
char again = '0';

while (again != '|')
{
cout << "Enter a number ";
cin >> number1;
cout << "Enter a second number ";
cin >> number2;
cout << "\n The integers are: " << number1 << " and " << number2 << "\n";
cout << "Enter | to end. ";
cin >> again;
if (again == '\n' || again == '\0')
again = '0';
cout << again <<"\n";
cout << "\n";
}
return 0;
}
][/code]
You can't enter '\n' or '\0' through std::cin operator>>, so your method isn't going to work.
You want '|' to end the loop, so why even check for '\n' or '\0'?

1
2
3
4
5
while (again != '|')
{
    cin >> again;
}
std::cout << "out of loop!" << std::endl;


What exactly do you want to happen if the user only presses Enter/Return at the "Enter | to end" prompt?
I think answering that will help us help you.

Also, you must put the code between the [code] delimiters -- between the ] and [, not inside the delimiters themselves.
Last edited on
Thank you for the reply. The reason I am checking for the '\0' and '\n' characters is because I am not sure which would be read as the return character. Entering return at the "Enter | to end" prompt should allow the loop to continue.
So you want typing the character '|' and typing nothing (and pressing enter) to both loop?

Something like this should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Example program
#include <iostream>
#include <string>

int main()
{
    std::cout << "Type some stuff:";
    std::string line;
    while (getline(std::cin, line))
    {
        std::cout << "You typed: " << line << '\n';
        if (line == "|" || line == "")
        {
            std::cout << "continuing loop...\n";
            continue;
        }
        else
        {
            std::cout << "breaking out of loop...\n";
            break;
        }
    }
    
    std::cout << "out of loop" << std::endl;
}
Last edited on
Topic archived. No new replies allowed.