简体   繁体   中英

how to read enter input on c

This function will be called by the menu.

void exponentiation()
{

  int i, result = 0, first, second;

  printf("\n%s\n%s\n\n%s",
         "1) Exponentiation",
         "------------------",
         "Enter 1st integer: ");
  scanf("%d", &first);

  printf("Enter 2nd integer: ");
  scanf("%d", &second);

  printf("%d raised to %d equals %d\n", first, second, result);
  main();
}

From this function I need to read the user input, if the user input is "enter" without any integer, it should be going back to the menu which is calling the main().

I already tried to get the input. For example:

if(first == '\n')

{main();}

or

if(first == 10) /**which is 10 is ASCII code for enter**/

{main()}

Both ways it didn't work at all, any suggestions?

both ways it didn't work at all, any suggestion

The function scanf returns the number of items it successfully scanned. You should check its return and go back if it doesn't matches your expectations.


Also you should know %d ignores whitespace . So if the user hits return without entering an integer, scanf simply skips over it and waits for something else.

If you insist on not ignoring whitespace this way, you should avoid scanf and use other input methods such as fgets . Get input from the user line by line and use sscanf , strtoul and strtok to make sense of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM