Convert string to int and get the number of characters consumed in C ++ using stringstream

I am new to C ++ (coming from C # background) and trying to learn how to convert a string to int.

I worked using stringstream and outputting it in double , for example:

 const char* inputIndex = "5+2"; double number = 0; stringstream ss(inputIndex); ss >> number; // number = 5 

This works great. The problem I am facing is that the lines that I am processing start with a number, but may have other digits after the digits (for example, "5 + 2", "9- (3 + 2)" etc.)., stringstream parses the numbers at the beginning and stops when it encounters a non-digit as I need it.

The problem arises when I want to know how many characters were used for analysis in number. For example, if I parse 25+2 , I want to know that two characters were used for parsing 25 so that I can advance the line pointer.

So far I have been working by clearing the stringstream , inserting the processed number into it and reading the length of the resulting string:

 ss.str(""); ss << number; inputIndex += ss.str().length(); 

While this works, it seems to me that it is really harmful (although it can only be because I come from something like C #), and I have a feeling that can cause a memory leak, because str() creates a copy of the string.

Is there any other way to do this, or should I stick with what I have?

Thanks.

+4
source share
2 answers

You can use std::stringstream::tellg() to find out the current receive position in the input stream. Store this value in a variable before retrieving from the stream. Then get the position again after retrieving from the stream. The difference between the two values ​​is the number of characters selected.

 double x = 3435; std::stringstream ss; ss << x; double y; std::streampos pos = ss.tellg(); ss >> y; std::cout << (ss.tellg() - pos) << " characters extracted" << std::endl; 
+6
source

A solution using the tellg () command will not be executed on modern compilers (for example, gcc-4.6).

The reason for this is that tellg () really shows the position of the cursor, which is now out of scope. See, for example, " tellg / tellp and gcc-4.6 file stream is an error? "

So you need to also check for eof () (which means that all input has been consumed).

+1
source

Source: https://habr.com/ru/post/1336900/


All Articles