Solved

C Programming read string from text file with commas

Posted on 2013-06-14
12
986 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
An API detour question 7 79
How to gracefully close the c++ 11 thread? 3 85
Dialogbox API leak? 18 83
How to access ANSI/IEEE Std 754 or equivalent information ? 3 46
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…

863 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

19 Experts available now in Live!

Get 1:1 Help Now