I have the following in a text file

How old are you?:I am 1 year old.

Basically, the ":" is the delimiter. "How old are you?" is the question and "I am 1 year old" is what i will reply when i get the question .

There is basically 2 fields in this. I know in C++ i can just do a getline(cin, question, answer,:) specifying the delimiter.

however, i cant do that in c? is there a better way to do it? store the first field in one string variable and 2nd field in another stirng variable?

9 Years
Discussion Span
Last Post by Salem

Read the whole line with fgets()

Tokenise is with strchr(), strtok() or anything else you can think of.


I've tried using fgets to read whole line.

However, it only reads the first line and end from there. Did i forget to put a loop or something?

#include <stdio.h>

int main()
FILE * pFile;
char mystring [300];

pFile = fopen ("question.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
while(fgets (mystring , 300 , pFile)) {
fgets (mystring , 300 , pFile);
puts (mystring);
fclose (pFile);
return 0;


You call fgets() twice, then close the file INSIDE the loop.

So yeah, you only go round the once.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.