Solved

C Programming read string from text file with commas

Posted on 2013-06-14
12
1,043 Views
Last Modified: 2013-06-14
here is my code so far


int main()
{
      char *first; // define first, last, and years
      char *last;
      int years;

      char str[256];
      first = str;
        last = str;

      years = atoi(str);
      float sal;

      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
   
    char *tokenPtr;
    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

      return 0;
}


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:

**USER INFO**

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. :)
0
Comment
Question by:clb92
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
12 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 39248760
Looks pretty OK, just a couple of things - the line

 fscanf(info, "%s, %s, %d",&first, &last, &years); // read from file, assign

Open in new window


should actually be

 fscanf(info, "%s, %s, %d",first, last, &years); // read from file, assign

Open in new window


since the arrays' names already are the address of the 1st element. Also, the commas in the format string will already skip the commas in the file, so there's no need to use 'strtok()', quote from the docs:

Characters outside format specifications are expected to match the sequence of characters in the input stream; the matching characters in the input stream are scanned but not stored.
0
 

Author Comment

by:clb92
ID: 39248795
That's what I thought when I used

fscanf(info, ......., ...);

but it doesn't work at all. When I use strktok the commas are ignored but the output is still:

First: Ima
Last: Ima
Age: 0 years old.

using text file containing "Ima, Student, 21"
0
 
LVL 86

Expert Comment

by:jkr
ID: 39248815
Ah, I see, the strings both point to the same buffer - try

      char first[256];
      char last[256];

      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

Open in new window


instead.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:clb92
ID: 39248824
Nope it got mad at that and spit out a bunch of characters before the first name on the last name line.
0
 
LVL 86

Expert Comment

by:jkr
ID: 39248983
Hm, then you should read the entire line at split it at the commas - which then can be done using 'strtok()'. Or manually.
0
 

Author Comment

by:clb92
ID: 39248994
Still not working. Thanks, though.
0
 
LVL 86

Expert Comment

by:jkr
ID: 39249020
What do you have now?

Reading the entire line would work like

      fgets(str,256,info); // read from file, assign

Open in new window


Then, parse the line into three strings like

      first = strtok(str,",");
      last = strtok(NULL,",");

Open in new window


What's left is to convert the last one to a number (if necessary at all)...
0
 

Author Comment

by:clb92
ID: 39249039
It worked for the last name part so thanks again! The age is still 0 years old. What do you suggest I do?

int main()
{
      char *first; // define first, last, and years
      char *last;
      int years;

      char str[256];
      first = str;
      last = str;
      
      years = atoi(str);
      float sal;

      FILE *info; // create info pointer
      info = fopen("info.txt","r"); // open text file called info, read
      
      
      fgets(str, 256, info); // read from file
        first = strtok(str, ",");
      last = strtok(NULL, ",");

      
      printf("\n**USER INFO**\n\nFirst Name: %s\n\nLast Name: %s\n\nAge: %d years old.",first, last, years); // print out information
0
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 39249057
You're using 'atoi()' even before 'str' is read, so that won't work. That could be like

      char* first;
      char* last;
      char* yr;
      int years;
      char str[256];

      FILE *info; // create info pointer
      info = fopen("info.txt","r"); // open text file called info, read
            
      fgets(str,256,info); // read from file, assign

      first = strtok(str,",");
      last = strtok(NULL,",");
      yr = strtok(NULL,",");

      years = atoi(yr);

Open in new window

0
 

Author Comment

by:clb92
ID: 39249063
This is what I just added:

char *years;
char str[256]; // already there
years = str;

int cvrtYears = (int)years;


it got rid of the 0 years old and put a really large number. I'm guessing it's the last name in ASCII?
0
 

Author Comment

by:clb92
ID: 39249075
It works, and I learned some new tricks today! Thanks so much!!
0
 
LVL 86

Expert Comment

by:jkr
ID: 39249089
>> I'm guessing it's the last name in ASCII?

No, that large number would be the address of the string in memory as an integer.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question