I am trying to understand how stringstream
works in order to be able to identify and convert possible numbers that were inputted as strings... for some reason this small piece of code I wrote to try and understand stringstream
is being annoying with a few errors...
#include <iostream>
#include <string>
using namespace std;
int str2int (const string &str) {
std::stringstream ss(str);
int num;
if((ss >> num).fail())
{
num = 0;
return num;
}
return num;
}
int main(){
int test;
int t = 0;
std::string input;
while (t !=1){
std::cout << "input: ";
std::cin >> input;
test = str2int(input);
if(test == 0){
std::cout << "Not a number...";
}else
std::cout << test << "\n";
std::cin >> t;
}
return 0;
}
Errors:
Error C2079:'ss' uses undefined class std::basic_stringstream<_elem,_traits,_alloc>'
Error C2228: left of '.fail' must have class/struct/union
Error C2440: 'initializing': cannot convert 'const std::string' into 'int'
what am I doing wrong?
How to Perform Extraction or Read Operation in StringStream in C++ Like the insertion, we can also perform extraction on StringStream in C++, like the cin >> operator. We can again do this by using the >> operator or the str() function.
For clearing the contents of a stringstream , using: m. str("");
myStream. rdbuf()->in_avail() can be used to get the count of available characters ready to be read in from a stringstream , you can use that to check if your stringstream is "empty." I'm assuming you're not actually trying to check for the value null .
A stringstream class in C++ is a Stream Class to Operate on strings. The stringstream class Implements the Input/Output Operations on Memory Bases streams i.e. string: The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings.
You need to include the following header file -
#include <sstream>
Whenever you see errors like undefined class
, you should always look for missing header files first.
Here is the documentation for the stringstream
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With