Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Some little help with string formatting in C

Name: Anonymous 2008-03-17 10:41

Hai guise, as mentioned above, I need some little help. Here's the thing:
I've been given a school project and I need to simulate an exam-date-organizer. OOP is prohibited, and I've gotta use C to code the program. Anyways, I've gotta read some text from a file and that's where I've got problem with.
Some parts of the text file has multiple data types in a single line. As in this format: "string,integer,string,integer,string\n". The problem is, the first and last string may (or WILL) contain blank spaces. fscanf function ignores character such as these, so I can't read the values correctly. Putting all string on separate lines is a solution, but I don't wanna put EVERYTHING on single lines, as it would take make it harder to read (for the user). Using a length-based reading function is another solution, but the string lengths may (or WILL) vary.

I made a quick search and found out that I can tell the application NOT to ignore blanks, etc, but it seems I can't use it well enough, as the function goes too far in the file, and skip some values. Here's an example:
The code block I use to read is:
fscanf(f,"\n%[A-z,^ ],%d,%s,%d,%s",lname,&cyear,lcode,&etime,name);
Data types for these variables are:
lname:char*, cyear:int, lcode:char*, etime:int, name:char*
What's written in the file is (on a single line):
Calculus II,0,MAT102,80,Some Guy
(lesson name,class year,lesson code,exam time in minutes,some guy's name)
The values I get for these variables get are:
lname: Calculus II, (including the comma)
cyear: 1
lcode: (nothing)
name: (nothing)
etime: 7

So, for short, I need to read comma-separated values from a single line, including the blanks, and skip to the next line with "\n". How do I do that?

Name: Anonymous 2008-03-17 12:50

Use a state machine.

while((c=getchar())!=EOF) {
 switch(c) {
  case ' ':
  case '\t':
   continue;
  case 'A': case 'B': ...
   /* collect bytes into an array here, checking for overflow as necessary */
   break;
  case ',':
   goto done_first_field;
 }
}
done_first_field:


You don't need to use a state machine completely, some things (like parsing the integers) could be handled with atoi(). But I'd write the main code as a form of state machine.

OOP is prohibited
Good. If you even consider using OOP for something as trivial as this, you should never program again.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List