简体   繁体   中英

In C++, how to extract a substring from a string (or char array) and write it to a string, without getting warnings?

In C++, I'm reading a file in which the lines are something like

     65-82 0.015 0.655

where the first is a string (tipically made of numbers separated by a dash or a comma, that then gets processed) and two floating point numbers. I'm currently reading them with the following code, with [line] being a character array:

std::string temp_string;
double temp_kb, temp_kt;
int res = sscanf(line, "%s %lf %lf",temp_string,&temp_kb,&temp_kt);

this yields a warning:

~/TEPInteraction.cpp:1002:76: warning: writing into constant object (argument 3) [-Wformat=]
int res = sscanf(line, "%s %lf %lf",temp_string.c_str(),&temp_kb,&temp_kt);
                                                                        ^

which of course makes sense, since c_str() returns a constant pointer. What would be the proper way of doing this without a warning?

Many thanks, Ferdinando

EDIT: The value of res was needed to do some controls further down the line, so I'll have to briefly rewrite my code so that it doesn't use it. It's not a big deal but It'll wait until tomorrow. Thanks guys :-) I really appreciate your help.

Since your input is space delimited you can get away with reading the input with the >> operator of the file stream.

std::ifstream fin("my_file_to_read");
std::string data;
double a, b;
fin >> data >> a >> b;

The above will take

65-82 0.015 0.655

from the file and input 65-82 into data and then stop at the space. Then 0.015 gets added to a and then stops at the space and then 0.655 gets added to b .

Since your input starts with a number if you want to make sure that you have 3 values per line then you would need to read in the whole line from the file using std::getline . Then you can load that line into a std::stringstream and check if the extraction succedes.

std::ifstream fin("my_file_to_read");
std::string data, line;
double a, b;
std::getline(fin, line);
std::stringstream ss(line);
if (!(ss >> data >> a >> b))
{
    //error handling code here
}

In C++ you would typically do something like:

std::istringstream stream(line);
std::string temp_string;
double temp_kb, temp_kt;
if (!(stream >> temp_string >> temp_kb >> temp_kt)) {
    // unable to read all values. handle error here
}

You cannot write to a string object like that. If you're really bent on using sscanf() , you'll need to use a char[] array instead and potentially convert that to a string afterward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM