Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using std::sscanf and std::string

Tags:

c++

string

scanf

I am wanting to "extract" the info from a string. The string is always in the format int int char.

I have spent solid hours on this, checked "every" example this site and google I found, to no avail. Some examples compiled, but crashed (no overflow.)

Here is the current, it compiles but crashes.

// Data                    
string str = "53 25 S";
int num1;
int num2;
char type3;

// Read values                                  
sscanf(str.c_str(),"%i %i %c",num1,num2,type3);
like image 412
Evan Carslake Avatar asked Dec 02 '22 16:12

Evan Carslake


2 Answers

You need the address of operator i.e.

sscanf(str.c_str(),"%i %i %c",&num1,&num2,&type3);
like image 96
Ed Heal Avatar answered Dec 20 '22 09:12

Ed Heal


The documentation for sscanf() should contain the answer to your question.

If you really insist on using sscanf(), then the addresses of num1, num2, and num3 need to be passed, not their values.

sscanf(str.c_str(),"%i %i %c",&num1,&num2,&type3);

You would be better off using a stringstream (declared in standard header <sstream>) than trying to use deprecated functions from C.

std::istringstream some_stream(str);
some_stream >> num1 >> num2 >> type3;
like image 33
Peter Avatar answered Dec 20 '22 08:12

Peter