Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Sep 20, 1999

Record Retrieveal Using fscanf

Question:
If three records have been written to a text file(each record having 3 int fields) and each integer field is seperated by a comma, how do you retrieve only the int values from each record (i.e no character retrieval)and print to screen using fscanf and printf?

For example, the file contains:
1,2,3,
4,5,6,
7,8,9,

The screen output should be:
1 2 3
4 5 6
7 8 9

Answer:
Although it isn't used much by C++ developers these days, scanf and fscanf provide a lot of functionality.

My preference would be to read each line into a buffer and then call sscanf. This gives you a little more control. But, given the file format you specified, you could easily read in the contents with the following code:


#include 

main()
{
   FILE* f;
   int a, b, c;

   f = fopen("c:\\test.dat", "r");
   if (f != NULL) {
      while(!feof(f)) {
         if (fscanf(f, "%d,%d,%d,\n", &a, &b, &c) != 3) {
            printf("Syntax error found in file.\n");
            break;
         }
         printf("%d %d %d\n", a, b, c);
      }
      fclose(f);
   }
   return 0;
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date