how to input multiple data types in c

68 views Asked by At

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

2

There are 2 answers

0
Allan Wind On BEST ANSWER
  1. char c[2] is needed hold a string with one character with the terminating '\0'.

    You could also use char c[1] or just char c and 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.

  2. Always use a maximum field width when reading a string with scanf() to avoid buffer overflow.

  3. The format string %s requires a matching char * which you write as just c.

  4. On success scanf() return the number of items successfully matched. If you don't check for that you may be operating on uninitialized variables.

  5. (Not fixed) If you only enter two numbers, scanf() will be waiting for the operator. If you don't want this behavior use fgets() or getline() to get a line of input. Then process that that with sscanf() or lower level functions like strtol(). This ensures you make progress by selecting what you need and discarding everything else. Separating I/O handling (checking for EOF) and parsing also leads to simpler code.

#include <stdio.h>

int main(void) {
    int a;
    int b;
    char c[2];
    if(scanf("%i%i%1s", &a, &b, c) != 3) {
        printf("scanf failed\n");
        return 1;
    };
    printf("%i %i %s\n", a, b, c);
}

Example run:

$ ./a.out
1 x
scanf failed
$ ./a.out
1 2 +
1 2 +
0
Itati On

Problem1: If you declare a string, it has a '\0' at the end, so you need increase array length, like c[2]. So it will be

[0] [1]
 +  '\0'

Problem 2: When input 2 3 +, c will get a space after 3, so you need to type 2 3+ to get +.