cfile-ioscanfeofline-by-line

Separately scanning a sentence and number(s) in C


Let's say I have a text file (hw.dat) that lists data (name, height(cm), weight(kg)):

Yuri            164     80 
Lai San Young   155     60
John Wayne      180     93

and the list continues.

I'd like to scan and print all of the data in this format:

name: Yuri, height: 164, weight: 80
name: Lai San Young, height: 155, weight: 60

and so on.

Here is my failed attempt (code segments). I intended to write code that reads the hw.dat file line by line while printing out the data line by line:

double h, w;
char name[100];

FILE *fr;
fr = fopen ("hw.dat", "r");

while (fscanf(fr,"%[^\n]s %lf %lf", name, &h, &w)!=EOF)
{
    printf ("name: %s, height: %lf, weight: %lf \n", name, h, w);
}

fclose (fr);

The %[^\n]s "eats up" the whole line. I also cannot use %s because the number of words of the names are different. So, I'm wondering if there is anyway to separate the scanning...or is there any better way to approach this problem...

Thank you.


Solution

  • Try

    fscanf(fr,"%99[^0-9]%lf%lf ", name, &h, &w)!=EOF)
    

    This will eat the name at the start of the line, then the numbers and then the new line.

    You will have to trim the name to remove the spaces at the end. How do I trim leading/trailing whitespace in a standard way? should help you