Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringstream errors c++

Tags:

c++

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?

like image 209
Gal Appelbaum Avatar asked Mar 22 '12 05:03

Gal Appelbaum


People also ask

Can we use Stringstream in C?

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.

How do you clear a Stringstream variable?

For clearing the contents of a stringstream , using: m. str("");

How do you check if a Stringstream is empty?

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 .

What does Stringstream mean in C++?

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.


1 Answers

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.

like image 133
MD Sayem Ahmed Avatar answered Oct 04 '22 02:10

MD Sayem Ahmed