Home > Blockchain >  Need help scanning an input in C
Need help scanning an input in C

Time:09-26

How would I scanf an input of "2 & 3"? Currently, I have it set up as

char expr[10]={};
printf("Enter the expression:");
scanf("%s", expr);

And at the moment it is just grabbing the 2.

CodePudding user response:

With scanf, the entry must be limited to the size of the buffer -1. In your case 9. To include white-space characters we use %[^\n], that means all the characters except '\n', which therefore makes %9[^\n]

#include <stdio.h>

int main(void)
{
    char expr[10];
    printf("Enter the expression: ");
    scanf("%9[^\n]", expr);
    puts(expr);

    return 0;
}

If you have other entries in a row, you should also purge the keyboard buffer to get out the characters entered in excess and the '\n' which has not been removed.

CodePudding user response:

As manual page described: The input string stops at white space or at the maximum field width, whichever occurs first. If you want to read a line from console, you can search "c get line" in google, you will get more results. for example: founction getline()

  •  Tags:  
  • c
  • Related