0

I am having a difficult time thinking of a way to extract a number such as an int or a double from a string extracted from the getline() function.

//Example:

string data = "";
fstream inFile;

//File contains:

"Hello today is 83.3 degrees Fahrenheit."

// use the getline function

getline(inFile, data);

// extract number from string data

Thank You

2 Answers2

0

You may do the following

getline(inFile, data);

std::istringstream iss;
iss.exceptions(std::istream::failbit | std::istream::badbit );

iss.str(data);
double dTemp = 0;

while( iss.good() ){

  try{
   iss >> dTemp;
   }      
  catch(std::istream::failure &e ){
   /* Do your error check over here */
  }

}

You make also want to read more about C++. Check this link

Hope this helps.

Community
  • 1
  • 1
0

You can use sscanf if you are prepared to include cstdio.

The following man pages link will help you:-

http://linux.die.net/man/3/sscanf

Example

char foo[] = "foo bar 12 baz";
int qux;
sscanf(foo, "foo bar %d baz", &qux); 
// qux will be assigned 12

or

char foo[] = "foo bar 12.5 baz";
double qux;
sscanf(foo, "foo bar %lf baz", &qux); 
// qux will be assigned 12.5 

You will obviously need to tailor this to your scenario and take various safety issues into consideration.

ed_me
  • 3,338
  • 2
  • 24
  • 34