Stubbsy
Stubbsy

Reputation: 27

Checking if a string is a number, then converting that number to an int?

The 'program' is to take input in then spit the string back out on seperate lines and all numbers are to be multiplied by two in this case.

My issue occurs when a number is input after a white space. Example

Sentence: 12 fish

Outputs:

24     
fish

But...

Sentence: there are 12

Outputs:

there
are
0

The program I have written:

#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;

int main()
{
    string str;
    int number = 811;
    cout << "Sentence: ";
    getline(cin,str);

    istringstream iss(str);

     while(iss)
     {
            bool ree = 0;
            string word;
            iss >> word;

            if(isdigit(word[0]))
            {
                stringstream(str) >> number;
                number = (number * 2);
                cout << number << endl;
                ree = 1;
                number = 911;
            }

           if(!ree)
           {
            cout << word << endl;
           }

           ree = 0;

      }
}

Hopefully it's something small I am not seeing! Thanks for the help in advanced.

Upvotes: 1

Views: 4928

Answers (3)

vsoftco
vsoftco

Reputation: 56547

The problem is that

stringstream(str) >> number;

creates a fresh string stream from the initial sentence, then tries to extract from it into number. Of course that will fail (as the first word in the sentence is not a number). If you wonder why number was set to 0, that's because on failure, the stringstream::operator>> zeros the argument (since C++11).

"If extraction fails, zero is written to value and failbit is set." ...

Before C++11, it left the argument unchanged. See the documentation for more details.

The correct way is to use a conversion from string to int (or long), namely std::stoi, and replace that line by

try{
    number = std::stoi(word); 
}
catch(std::exception& e){
    std::cout << "error converting" << '\n';
}

Upvotes: 6

ThisGuyCantEven
ThisGuyCantEven

Reputation: 1267

using stoi is easy, and you can lazily catch the exception by the following:

if(!stoi(string)){
    std::cout << "caught a non integer string" << endl;
}

Upvotes: -2

Devin L.
Devin L.

Reputation: 447

Use stoi to parse the input like this:

int num = std::stoi(input);

Upvotes: 0

Related Questions