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?

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);
system("pause");
}
return 0;
}

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

So yeah, you only go round the once.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.