-1

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.

  • 5
    Yes, because that's what `%s` does in `scanf`, see https://man7.org/linux/man-pages/man3/scanf.3.html. Here it clearly says that `%s` **matches a sequence of non-white-space characters**, so it will stop reading after the empty space after the `2`. My advice is to **not use** `scanf` at all (unless your really know how this function behaves) and instead use `fgets` to get the whole line and then parse it in a separate step with `sscanf` or some other function. – Pablo Sep 26 '22 at 02:11
  • in addition to what @Pablo said, scanf has as it stands, no check on the length of the string so if somebody enters a 11 char string you have undefined behavior causing your program to potentially crash. – AndersK Sep 26 '22 at 04:20
  • Look into the `fgets` function. – Jabberwocky Sep 26 '22 at 06:22

2 Answers2

1

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.

CGi03
  • 452
  • 1
  • 3
  • 8
0

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()