C Programming read string from text file with commas
Posted on 2013-06-14
here is my code so far
char *first; // define first, last, and years
first = str;
last = str;
years = atoi(str);
FILE *info; // create info pointer
info = fopen("info.txt","r"); // open text file called info, read
fscanf(info, "%s, %s, %d",&first, &last, &years); // read from file, assign
tokenPtr = strtok(str, ","); // supposed to ignore comma
printf("\n**USER INFO**\n\nFirst Name: %s\n\nLast Name: %s\n\nAge: %d years old.",first, last, years); // print out information
scanf("%f", &sal); // keeps black box from disappearing
//fclose(info); // close info
I'm a computer engineering major at my school and I'm learning C for my internship. I have taken a C++ class but that was about two years ago so I'm rusty. I've been doing some practice coding with I/O and got stuck on this one. Anywho, the goal of this program is to read a file, grab three separate values and print out the information.
For example, the file info.txt would have:
Ima, Student, 20
and output would be:
First Name: Ima
Last Name: Student
Age: 20 years old.
How do I make the program ignore the commas and grab each string separately instead of making it one string? (do I need a loop? how would I go about implementing it?) At one point, I had the program print out the first name only and then where the last name there was the first name again and the age was 0 years old.
Any help would be greatly appreciated. :)