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?
You need to include the following header file –
Whenever you see errors like
undefined class, you should always look for missing header files first.Here is the documentation for the
stringstreamclass.