简体   繁体   中英

Why does printf only print the first word in a string?

I'm fairly new to C programming, so I was playing around with reading data from a file using fgets() and sscanf(). I set up a real simple experiment here:

#include <stdio.h>
#include <stdlib.h>

main()
{
    char szInputBuffer[100];
    FILE *pFile;
    char szInput[100];
    int i;

    pFile = fopen("MyFile.txt", "r");
    printf("This is the input: \n\n");

    for (i = 0; i <= 2; ++i)
    {
        fgets(szInputBuffer, 100, pFile);
        sscanf(szInputBuffer, "%s", szInput);
        printf("%s", szInput);
    }
}

I am reading from MyFile.txt which contains simply:

This is more input.
The next line of Input.
More input here.

How ever my output is:

This is the input:
ThisTheMore

Which is the first word from every line. I found that when I add a second %s to the printf statement like so:

printf("%s%s", szInput);

That I achieve the desired output:

This is the input:
This is more input.
The next line of Input.
More input here.

Can someone please explain this to me? I have never heard of using a second placeholder to get the entire string. I have not been able to find anything that helps with my issue here. I have seen example programs in class that only use one %s in the print statement and the entire string is printed. Thanks for helping out a curious programmer!

PS I am running Ubuntu 14.04 LTS, using the Geany IDE. I know some of you guys ask about that.

sscanf(szInputBuffer, "%s", szInput);

The format specifier %s fetches the string until a space or newline character is encountered so you are just getting a single word in order to get the whole line just nul terminate the string after fgets() as fgets() comes with a newline character and print out the string.

The scanf() man says %s

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

Do

size_t n;
fgets(szInputBuffer, 100, pFile);
n = strlen(szInputBuffer);
if(n>0 && szInputBuffer[n-1] == '\n')
 szInputBuffer[n-1] = '\0';
 printf("%s\n",szInputBuffer);

If you are looking to break the line into strings and print out each word in a line then go for strtok() with space as delimiter.


If you see

printf("%s%s", szInput);

working then what you have is undefined behavior.printf() says that the number of format specifiers should match number of values which needs to be printed out . Note that even with type mismatch the behavior is undefined .

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