0

I am trying to use fscanf() to read names from a text file in c. However, the names in this file are not separated by white-spaces. Can I still separate out each name using this function?

At the moment, the file contains this text :

"MARY","PATRICIA"

And when I run the following code :

FILE *nameFile;
char name1[100];
char name2[100];

nameFile = fopen("names.txt","r");

fscanf(nameFile, "%s,%s", name1, name2);
printf("name 1 : %s\n name 2 :%s\n", name1, name2);

fclose(nameFile);

I get the following output :

name1: "MARY","PATRICIA"
name2:

Is there any way of separating the names out without having spaces in the file?

Oliver Redeyoff
  • 177
  • 2
  • 14

1 Answers1

3

You have to instruct the fscanf() to look for another delimiter, cutting the fields (using %[ formatter).

Please, try this:

#include <stdio.h>

int main(int argc, char *argv[])
{
   FILE *nameFile;
   char name1[100];
   char name2[100];

   nameFile = fopen("names.txt","r");
   fscanf(nameFile, "%[^,],%[^,]\n", name1, name2);
   /* or fscanf(nameFile, "%[^,],%s\n", name1, name2); for second string */

   printf("name 1 : %s\n name 2 :%s\n", name1, name2);

   fclose(nameFile);

   return(0);
}
  • 2
    3 weaknesses: 1) No width limit like `"%99[^,],%99[^,]\n"` 2) code does not check the return value of `fscanf()`. 3) `"\n"` can read in multiple lines. – chux - Reinstate Monica Mar 31 '19 at 22:05
  • Another shortcoming: `%[^,],` cannot handle empty fields which are common in CSV files. – chqrlie Apr 01 '19 at 12:55
  • 2
    Note that [trailing white space in a `scanf()` format string is evil](https://stackoverflow.com/questions/19499060/) if the input will come from a user rather than a file. From a file it is usually OK, but it is better to avoid trailing white space (skip leading white space with a blank at the start of the format string). – Jonathan Leffler Apr 01 '19 at 14:30
  • It is a answer to a specific question about fscanf(), not a "project request". I personally do not like fscanf(), i will not do it with fscanf(). And where is your best answer to me give a vote up?? – André A. G. Scotá Apr 01 '19 at 16:44