0

this code is ment to get 4 variables from an input file and then to take those 4 variable and add +1 to other variable(havnt added yet) but when I tested in values taken it came with some good answers but also a ton of bad values that I dont know how to fix.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void)
{
    int counter = 0;
    FILE* infile = fopen("input.txt", "r");// input file with 4 variabels.
    typedef struct person// struct for 4 variables
    {
        char gender;
        char gamer;
        char toxic;
        int age;
    }person;

    person people[50];
    while (!feof(infile))// continue until end of file 
    {
        fscanf(infile, "%c", &people[counter].gender);//grabs letter for gender (M/F)
        fscanf(infile, "%c", &people[counter].gamer);// grabs letter for gamer (Y/N)
        fscanf(infile, "%c", &people[counter].toxic);// grabs letter for toxic (Y/N)
        fscanf(infile, "%d", &people[counter].age);// grabs int for age (#)
        printf("%c\n%c\n%c\n%d\n", people[counter].gender, people[counter].gamer, people[counter].toxic, people[counter].age);// was checking for if the variable were getting correct inputs
        ++counter;// Updates counter for next person
    }

}

It keeps returning some values but also some weird values.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Can you show what the input file looks like? – Barmar Apr 07 '22 at 16:57
  • m \n y\n y \n 12 (each input has its own line) – kilamonjaro Apr 07 '22 at 16:59
  • Your code expects all the characters to be connected, with no spaces between them, like `MYN`. – Barmar Apr 07 '22 at 16:59
  • 1
    Put a space before each `%c` to skip over the newlines. – Barmar Apr 07 '22 at 16:59
  • Is your file like "FYY345FYY234FYY53"? See [feof](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – Neil Apr 07 '22 at 16:59
  • 1
    Also see [Why `while(!feof(file))` is always wrong](https://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – Barmar Apr 07 '22 at 17:00
  • After adding the spaces I got these results (m ╪ ` -1956644814 ) with this code (fscanf(infile, " %c %c %c %d", &people[counter].gender, &people[counter].gamer, &people[counter].toxic, &people[counter].age);) – kilamonjaro Apr 07 '22 at 17:02
  • Neil, yes my inputs should look like that but with each input having its own line – kilamonjaro Apr 07 '22 at 17:05
  • " %c %c %c %d" is a reasonable format string, but also make sure to check the [return value of scanf](https://pubs.opengroup.org/onlinepubs/007908799/xsh/fscanf.html). – Neil Apr 07 '22 at 17:16

0 Answers0