I need to get in one single shot different inputs from one single line. In particular I need to get a single char
and then, depending on which char
value I just read, it can be a string and an int
or a string, an int
and another string and so on.
A sample input might be:
c test 20 good
d test 10
This is what I wrote:
char c, * alpha, * beta;
int val;
c = getchar();
printf("%c\n\n", c);
switch (c){
case 'd': scanf("%s %d", alpha, &val); printf ("%c %s %d", c, alpha, val); break;
case 'c': scanf("%s %d %s", alpha, &val, beta); printf ("%c %s %d %s", c, alpha, val, beta); break;
default: return 0;
}
Besides it needs a newline (i.e. me pressing return) to get the first char, it works fine for the d
case but goes in segfault in the c
case. How should I do so?
Best How To :
I'm not saying that it cannot be done using scanf()
, but IMHO, that's not the best way to do it. Instead, use fgets()
to read the whole like, use strtok()
to tokenize the input and then, based on the first token value, iterate over the input string as required.
A generic algorithm will look like
- Read a whole line using
fgets()
- Tokenize using
strtok()
using the space (
) as delimiter.
Take the first token, compare it to the desired input option c
or d
in your case.
NOTE: don't confuse the character 'c'
, 'd'
and string "c"
, "d"
- Based on the token value, you can add more call to
strtok()
on the same string to get the values for the remaining data in the input, you can make use of the existing switch-case
approach. Generally, continue until strtok()
returns NULL.
That said, to answer your question,
it works fine for the d
case but goes in segfault in the c
case.
The reason is, in the current program, your code invokes undefined behaviour, as you're using uninitialized pointers alpha
and beta
. You need to allocate memory to them before using, maybe through malloc()
and family.