mico
mico

Reputation: 9

how can I use scanf() to read a file including space in C

I am not allowed to call any function other in a C library other than scanf, printf, and feof. When I try to use the code below, it only reads a file up to space char. Is there a way to read a whole line without using "%[^\n]"? My end goal is to read the entire file using feof file but first, I need to know how to read a line using scanf. Is it possible?

#include <stdio.h>
int main(){

  char ar[50];

  scanf("%s", ar);
  printf("%s", ar);

}

Upvotes: 0

Views: 104

Answers (1)

chux
chux

Reputation: 153358

Read one character at a time.

#include <stdio.h>
int main(void) {
  char ch;
  while (scanf("%c", &ch) == 1) {
    printf("%c", ch);
  }
}

P. S. Don't ever do this for production code and never admit your did this on a résumé.

Follow @zwol advice.


"My end goal is to read the entire file using feof file " --> Why is “while ( !feof (file) )” always wrong?.

Upvotes: 1

Related Questions