I'm trying to write a program calculates based on keyboard input like a b c, a is number 1, b is number2 and c is operator but it's doesn't allow me to assign b when I use string, it doesn't show c when I use char can someone explain how this work please and how can I input multiple data types I'm new to C and i tried C++ before it's easier to input them
#include <stdio.h>
int main() {
int a , b;
char c[1];
scanf("%i%i%s", &a, &b, &c); //type 2 3 +
printf("%i %i %s",a,b,c);
}
the output is 2 0 +
and when i tried to use char #include <stdio.h>
int main() {
int a , b;
char c;
scanf("%i%i%c", &a, &b, &c);
printf("%i %i %c",a,b,c);
}
the output is 2 3 it's not showing c nor recognise it
char c[2]is needed hold a string with one character with the terminating'\0'.You could also use
char c[1]or justchar cand read a single non-space character with%c(space prefix is significant). When you print the character you then need to use the%c(instead of%s) conversion specifier.Always use a maximum field width when reading a string with
scanf()to avoid buffer overflow.The format string
%srequires a matchingchar *which you write as justc.On success
scanf()return the number of items successfully matched. If you don't check for that you may be operating on uninitialized variables.(Not fixed) If you only enter two numbers,
scanf()will be waiting for the operator. If you don't want this behavior usefgets()orgetline()to get a line of input. Then process that that withsscanf()or lower level functions likestrtol(). This ensures you make progress by selecting what you need and discarding everything else. Separating I/O handling (checking forEOF) and parsing also leads to simpler code.Example run: