Solved

C Programming read string from text file with commas

Posted on 2013-06-14
12
999 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
  • 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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
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 how to use strings and some functions related to them in the C programming language.

803 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