开发者

How to exit a program when user inputs a special character

开发者 https://www.devze.com 2023-03-01 15:21 出处:网络
i\'m curently doing a simple program that consists of a while-loop that reads in开发者_如何学运维 two ints and then prints them out. My question is, how can I exit the program when the user inputs the

i'm curently doing a simple program that consists of a while-loop that reads in开发者_如何学运维 two ints and then prints them out. My question is, how can I exit the program when the user inputs the caracter "|"? Here is this little super simple program:

int main()
{
    int var1 = 0;
    int var2 = 0;

    while(cin>>var1>>var2)
    {
        cout << var1 << " " << var2 << endl;
    }

    return 0;
}

I know that you can define an argument to getline that does exactly what I want to do, but I don't know how to implement this in a while-loop. Thanks for the help.


Your loop will already exit as soon as someone enters something istream cannot << into an integer. Anyway to exit specifically at |, I would use the peek function like so:

int main()
{    
  int var1 = 0;    
  int var2 = 0;
  while( cin.good() )
  {
    char c;
    c = cin.peek();

    if( c == | )
      break;
    else
    {
      cin >> var1 >> var2;
      cout << var1 << " " << var2 << endl;
    }
  }

  return 0;
}

It avoids using c-style input or complex line parsing.


All you have to do is to check if the value that was input was | in an if-block and then use the break keyword to stop the loop.

Something in the lines like this:

#include <stdio.h>
int main() {
    char c;
    for(;;) {
        printf( "\nPress any key, Q to quit: " );

        // Convert to character value
        scanf("%c", &c);
        if (c == 'Q')
            break;
    }
 } // Loop exits only when 'Q' is pressed


As written, you'll exit the loop if the user enters |. Or anything else that cannot be interpreted as an int (after skipping leading white space).

If you want more precise control, you'll have to read line by line (and parse the line), or character by character (and build up the values).

0

精彩评论

暂无评论...
验证码 换一张
取 消