Why doesn't a reference to an object of type istringstream
retain its last read character position after passing it to one function after another? I'm trying to use it similar to how a Scanner
object in Java works.
The goal is to create a function that loops through the characters of a string, which contains a signed decimal e.g. "-14.6"
, and return a signed integer out of it.
For that I use istringstream
on std::string
, then I pass the istringstream
object to one function after another, where each function reads a specific part of the decimal.
The first function reads two char
s, as white spaces, from the example string " -14.6"
, from the istringstream
object. The problem is that the second function, which should start reading the negative sign, starts reading all over again from the beginning of the string, and the position of the istringstream
object is not saved.
The code looks like this:
void read_whitespace (std::istringstream &ss);
bool read_sign (std::istringstream &ss);
std::string read_digit (std::istringstream& ss);
void convert_string(const std::string& s);
int main() {
std::string s = " -14.6";
convert_string(s);
return 0;
}
void convert_string (const std::string& s) {
std::istringstream ss(s);
bool sign = false;
// This function correctly reads the two white spaces
read_whitespace(ss);
// But _here_ ss starts reading again from the beginning of s
read_sign(ss);
read_digit(ss);
}
void read_whitespace (std::istringstream &ss) {
char c;
while (ss.get(c)) {
if (c == ' ') {
} else {
break;
}
}
}
bool read_sign (std::istringstream &ss) {
char c;
while (ss.get(c)) {
if (c == '-') {
return false;
} else { break; }
}
return true;
}
Aucun commentaire:
Enregistrer un commentaire