1

CODE :-

while ( fscanf ( fp,"%s %d %f", e.name, &e.age, &e.bs ) !=EOF )
{
    printf ( "%s     %d     %f\n", e.name, e.age, e.bs ) ;
} 

Say I am having following sentences in a file:-

fname lname 20 200000

fname1 lname1 30 50000

The desired output is :-

fname lname     20     200000.0000

fname1 lname1     30     50000.0000

But the output I am getting is :-

fname     (garbage value)     (garbage value)
 
lname      20     200000.0000

fname1     20     200000.0000

lname1     30     50000.0000

The above problem is due to the fact that %s do not read white spaces, hence it is splitting my fname lname into two parts.

Is there any solution to get the desired output?

Community
  • 1
  • 1
kevin gomes
  • 1,775
  • 5
  • 22
  • 30

1 Answers1

1

You need to use %s %s in your fscanf and read the first name and last name into separate variables, then concatenate them manually. (Use snprintf with %s %s as your format string.)

char first[200], last[200];
while (fscanf(fp, "%200s %200s %d %f", first, last, &e.age, &e.bs) == 4)
{
    snprintf(e.name, sizeof(e.name), "%s %s", first, last);
    printf ( "%s     %d     %f\n", e.name, e.age, e.bs ) ;
} 

If names can sometimes have more than two parts, you will need to use something more advanced to parse the string (a regular expression would be one approach), or to continue using fscanf, you'd need to insert an explicit separator character between the name and the numbers.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
  • `fscanf` returns the number of matches it found. It's going to match 4 things. Any less and it failed in the middle. – StilesCrisis Feb 27 '14 at 18:49
  • `fscanf` was returning 3 in your code. `EOF` isn't 3. – StilesCrisis Feb 27 '14 at 18:52
  • then how my `while loop` ended? – kevin gomes Feb 27 '14 at 18:53
  • `fscanf` does return `EOF` once the file is exhausted. – StilesCrisis Feb 27 '14 at 18:53
  • `If names can sometimes have more than two parts, you will need to use something more advanced to parse the string (a regular expression would be one approach), or to continue using fscanf, you'd need to insert an explicit separator character between the name and the numbers`...please show a example to illustrate this. – kevin gomes Feb 27 '14 at 19:03
  • Actually I was thinking the same, this answer cannot support string with more than one space, I was reading another post [here](http://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf), however I am not able to think of any regex to fit for your problem, still thinking a more general answer – shole Feb 27 '14 at 19:16
  • Off the top of my head, `^(.+)\s+(\d+)\s+(\d+)$` would be one way to regex it. You might need to trim the name. And of course, parsing a regex in C++ is a fair bit of code and depends on which library you use. – StilesCrisis Feb 27 '14 at 19:56