2
#include "stdio.h"

int main(){
    char str[20];
    while(scanf("%19[^\n]",str)==1){
        printf("%s",str);
    }
    return 0;
}

Compiled using:

$ gcc file.c -o file
$ file < input.txt

The program is reading only first line from the file input.txt :

hello this is
a test that
should make it
happen

I want the program to read the complete file, please help

brianmearns
  • 9,581
  • 10
  • 52
  • 79
  • 2
    Read that : http://stackoverflow.com/questions/3463426/in-c-how-should-i-read-a-text-file-and-print-all-strings and never use scanf. – Nuz Mar 18 '14 at 15:22
  • 1
    What is `[^\n]`? Is that an attempt at a “not a newline” character class regex in a `scanf()` format string? – Emmet Mar 18 '14 at 15:24
  • 1
    @Emmet Character classes are supported by `scanf`. They look similar to regex character classes. – interjay Mar 18 '14 at 15:29
  • actually i wanted to use this to write a c program that reads another c program and creates it flow graph. i assume here that the file does not contain any error and code is written according to LOC – sensitive_piece_of_horseflesh Mar 18 '14 at 15:32
  • @interjay: so they are! And have been for years. I never knew that. I guess that's what you get for not even looking at `scanf()`. – Emmet Mar 18 '14 at 15:44

2 Answers2

5

Add a space:

while(scanf(" %19[^\n]",str)==1){
             ^

The space (unintuitively) consumes any white-space, including the \n, which otherwise you are not handling.

Of course, it is generally better to use e.g. fgets() and sscanf() rather than scanf() to parse input.

This changes the logic of you code slightly, but maybe better captures your intent. Any attempt to only skip only \n rather than all white-space, as in:

while(scanf("%19[^\n]\n",str)==1){

will fail, because here the second \n is exactly the same as a space .

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
0

Find the modified code

#include <stdio.h>

int main()
{
    char str[20];
    while(gets(str)!=NULL)
    {
      printf("%s",str);
    }
    return 0;
}
M Thotiger
  • 344
  • 1
  • 7