Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use the following code to do it.</p> <p>Your problems were that you weren't checking the return from <code>fscanf</code> and that you weren't actually reading the newline (so the next time you read, you wouldn't go to the next line).</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;string.h&gt; #include&lt;stdlib.h&gt; int main (void) { FILE *fp; int x; fp=fopen("mydata.txt","r"); if(fp==NULL) { perror("Error while opening"); exit(0); } char *s=(char*)malloc(100); while(!feof(fp)) { x = fscanf(fp,"%[^\n]",s); fgetc(fp); if (x == 1) printf("%s\n",s); } return 0; } </code></pre> <p>However, if all you're after is the ability to input and process lines, <code>fgets</code> is a better solution than <code>fscanf</code> since there's no chance of buffer overflow:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define OK 0 #define NO_INPUT 1 #define TOO_LONG 2 static int getLine (char *prmpt, char *buff, size_t sz) { int ch, extra; // Get line with buffer overrun protection. if (prmpt != NULL) { printf ("%s", prmpt); fflush (stdout); } if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; // If it was too long, there'll be no newline. In that case, we flush // to end of line so that excess doesn't affect the next call. if (buff[strlen(buff)-1] != '\n') { extra = 0; while (((ch = getchar()) != '\n') &amp;&amp; (ch != EOF)) extra = 1; return (extra == 1) ? TOO_LONG : OK; } // Otherwise remove newline and give string back to caller. buff[strlen(buff)-1] = '\0'; return OK; } </code></pre> <p>&nbsp;</p> <pre><code>// Test program for getLine(). int main (void) { int rc; char buff[10]; rc = getLine ("Enter string&gt; ", buff, sizeof(buff)); if (rc == NO_INPUT) { printf ("No input\n"); return 1; } if (rc == TOO_LONG) { printf ("Input too long\n"); return 1; } printf ("OK [%s]\n", buff); return 0; } </code></pre> <p>Sample runs with 'hello', <kbd>CTRL</kbd><kbd>D</kbd>, and a string that's too big:</p> <pre><code>pax&gt; ./qq Enter string&gt; hello OK [hello] pax&gt; ./qq Enter string&gt; No input pax&gt; ./qq Enter string&gt; dfgdfgjdjgdfhggh Input too long pax&gt; _ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload