Click here to Skip to main content
15,891,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to read in a file that looks something like this:

Dom 69.5 1.80
Leigh 51.1 1.62


It must read in the first part(the name) as a string, and the next two values as floats.
Posted

one way is to use sscanf
like,
C++
char text[] = "Dom 69.5 1.80";
sscanf(text,"%s %lf %lf",&str, &d1, &d1);


or strtok like,

C++
char stringa[] = "Dom 69.5 1.80";
    char seps[]   = " ,\t\n";

   token = strtok( stringa, seps ); 
   
   // 1st one string
   printf( " %s\n", token );
      
   //2nd double
   token = strtok( NULL, seps ); 
   double d1 = strtod(token, NULL);
   printf( " %lf", d2);
   
   //3nd double
   token = strtok( NULL, seps );
   double d2 = strtod(token, NULL);
  printf( " %lf", d1);
 
Share this answer
 
Comments
PrafullaVedante 4-Aug-11 7:18am    
My 5.
DominicZA 4-Aug-11 11:30am    
sscanf is working when I need to extract the doubles, but it is not setting the value of the string?
The C++ way is to use streams, rather than the C library functions.

Something like this:

C++
#include <string>
#include <fstream>
#include <vector>

// Data structure for a line from file
struct FileLine
{
  std::string name;
  float f1, f2;
};

// Reading a line from stream
FileLine ReadLine(std::istream& in)
{
  FileLine line;
  in >> line.name >> line.f1 >> line.f2;
  return line;
}

void ReadFile()
{
  // Open stream from data file
  std::ifstream in("datafile.dat");
  // Read stream
  while (!in.eof())
  {
    FileLine l = ReadLine(in);
    // do whatever
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900