Solved

C Programming read string from text file with commas

Posted on 2013-06-14
12
976 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
 

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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
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.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

708 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now