I was trying get solution to this question. I tried this code with gcc as the compiler and the output was not as expected.

#include <stdio.h>

int main(void)
{

    char s1[10],s2[10],s3[10];
    scanf("%s,%s,%s ",s1,s2,s3);
    printf("%s\n",s1);

}

Input

abc,def,ghi

Output

abc,def,ghi

I am printing only the string s1 but it has the whole string.
Why doesn't scanf() read the input in such a way by breaking the input into 3 strings?

有帮助吗?

解决方案

No, scanf() doesn't know that it should stop the first string conversion at the comma, since a string can contain the comma.

You can do this using the %[] conversion specifier, use %[^,] to include all characters except the comma.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top