Problem in file handling in while reading file

The file "string.txt" contains a string "Hello World!". When I print ch, the out put shown on screen is only "HelloWorld!". Why?
1
2
3
4
5
6
7
8
9
10
11
12
13
  #include<stdio.h>
int main()
{
	FILE *file;
	char ch[10];
    file=fopen("D:\String.txt","r");
    while((fscanf(file,"%s",ch))!=EOF)
    {
    	x++;
    	printf("%s",ch);
	}
	fclose(file);
}
Last edited on
That is why we need to use C++ not C. C++ offers more functionality than you think.

You can solve the problem by simple std::cin coupling with std::noskipws.
When I print ch, the output is HelloWorld!

Because the '%s' format specifier reads individual tokens as strings, skipping whitespace.
You should add a maximum width specifier.

http://en.cppreference.com/w/c/io/fscanf#Parameters
Last edited on
Topic archived. No new replies allowed.