user75521
user75521

Reputation: 59

How to use scanf to read each line of a file with space?

So I'm trying to write a c program that can read each line of a file pass to it by command line and print out each line. My code look like this:

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

int main(void){

        char num[20];
        for (;;){
                if((scanf("%[^\n]s", num)) != 1){
                        break;
                }
                printf("%s\n", num);
        }
}

The unix command line is: ./printeachline < num.txt

the num.txt includes these lines:

01 0111111119
111122222228
123400000000
1234kk444k44
oooo11111111
o dk39754i2oo
002711111116
124145245 246623
0027111111167
888888888888
100900000011

What I'm expecting to print out is every line in num.txt, However when I enter the command only the first line is printed, that is 01 0111111119. How could I fix this????

Upvotes: 0

Views: 9503

Answers (4)

Vinay Tiwary
Vinay Tiwary

Reputation: 305

If you want to read from file then better use file operations. You can refer to this http://www.thegeekstuff.com/2012/07/c-file-handling/

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

The answer to your question is not how to use scanf() to solve your problem, but rather use fgets() instead. scanf() is known to be error-prone, may cause buffer overflow, etc. fgets() is the function that's designed to be used to process each line:

while (fgets(num, sizeof num, fp) != NULL)
{
    printf("%s", num);
}

fp is the FILE * pointer for num.txt.

Upvotes: 7

LearningC
LearningC

Reputation: 3162

you can use fgets() or if you are using GNU C then you can use getline() to read the input line by line. Or you can add a getchar() in loop in your program then the program will work. It reads the newline character left by scanf().

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

int main(void){

char num[20];
for (;;){
if((scanf("%[^\n]s", num)) != 1){
break;
}
printf("%s\n", num);
getchar();
}
}

Upvotes: 1

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

Your scanf leaves the newline at the end of the line, so the next scanf will fail. Add a getchar() to read and throw away the newline character.

But, as others have said, use fgets instead.

Upvotes: 0

Related Questions