简体   繁体   中英

scanning a line of strings with spaces using scanf

I was using scanf for all my inputs in C. Now I saw other similar questions about scanf() and they suggested using fgets() instead of scanf() . I will do so in the future. However, at the moment this particular part of code with scanf() never seems to work. I know there is a solution.

My code is:

#define LENGTH 1000
#define WORD 100
int main(){
    int i = 0;
    char s[WORD][LENGTH];
    do {
        scanf("%s", s[i]);
        i++;
    }
    while (s[i][strlen(s[i])] != EOF);
    printf("%s\n", s);

    return 0;
}

There should be something instead of EOF in the while loop which checks for the end of line. The final result should be an array of words in s[] and the program should print that array of words without spaces.

Unfortunately scanf() does not read the character you need to check for end of line, or at least not using "%s" as the specifier.

Instead, use the following

char line[100];
if (scanf("%99[^\n]", line) == 1) {
    fprintf(stdout, "%s\n", line);
}

This way, it does not stop at white space characters, and it behaves similar to fgets() , except that it does not read the '\\n' character and that might be a problem if you call it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM