0

I want the result to be appear as

Here is your name: John
Here is your Date of birth: 02/02/1999

Although name, DOB are present in array and I am successfully fetching those values of name, dob etc. But the problem is that it is giving me this problem.

Here is your name: John
Here is your name: 02/02/1999
Here is your name: 442342352

Means with every value it is giving me only name, although everything is present in array.

#include <stdio.h>
#include <stdlib.h>

int main(){
    const char listings[5][51] = {"Name", "Date of birth","ID card number","Phone number","Address"};
    FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
    char ch[100];
    int index = 0;
    for (int i=0; i<5; i++){
        if(fr != NULL){
            while((ch[index] = fgetc(fr)) != EOF){
                if(ch[index] == ' ') {
                    ch[index] = '\0';
                    printf("Here is your %s: %s\n",listings[i], ch);
                    index = 0;
                }
                else {
                    index++;
                }
            }
            fclose(fr);
        }
        else{
            printf("Unable to read file.");
        }
    }
    return 0;
}
2
  • You shouldn't close the file inside the for loop. Commented May 15, 2020 at 1:12
  • The for loop should be inside the if (fr != NULL) test, not the other way around. Commented May 15, 2020 at 1:13

1 Answer 1

1

You are looping through the whole at once, your 'i' is never incremented. Then, increment it inside the while loop.

while((ch[index] = fgetc(fr)) != EOF){
       if(ch[index] == ' ') {
           ch[index] = '\0';
           printf("Here is your %s: %s\n",listings[i], ch);
           index = 0;
           i++;
       }
       else {
             index++;
       }
   }

Don't forget to erase the for loop.

Sign up to request clarification or add additional context in comments.

4 Comments

i is the iteration variable of for (int i = 0; i < 8; i++)
You need a different variable for the index into listings.
If for loop erased then how will I put value of i?
Just initialize it with zero out of the while loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.