0

I am trying to write a c ++ program that read a string and print out all the integers that can be read in this string. For example if s="-1b34ggg--54-7-t--". the program should print : -1 34 -54 -7. Below is my code but it does not work. It just print out the positive integers.

#include<string>
using namespace std;
bool isNumber(string s)
{
    for (int i = 0; i < s.length(); i++)
        if (isdigit(s[i]) == false)
            return false;
 
    return true;
}
int main(void)
{
    string s;
    s="-1b34ggg--54-7-t--";
    string temp="";
    for(int i=0;i<s.length();i++)
    {
        if(isdigit(s[i]))
        {
            temp+=s[i];
        }
        else if(s[i]=='-')
        {
            
            if(isNumber(temp))
            {
                cout<<atoi(temp.c_str())<<" ";
                temp="";
                temp+=s[i];
            }
            else
            {
                temp="";
                temp+=s[i];
            }
        }
        else
        {
             if(isNumber(temp))
             {
                cout<<atoi(temp.c_str())<<" ";
             }
             temp="";
        }
    }
    return 0;
}
  • did this answer your question: https://stackoverflow.com/questions/44330230/how-do-i-get-a-negative-value-by-using-atoi – Kraego Jun 09 '21 at 08:11

2 Answers2

0

s[0] can contain - or + sign. you did not check it.

bool isNumber(string s)
{
    if (s.empty()) return false;
    if ((s[0] == '-' || s[0] == '+') && s.length() == 1)
        return false;
    
    for (int i = 1; i < s.length(); i++)
        if (isdigit(s[i]) == false)
            return false;
    
    return true;
}
0

Ok problem solved! Big thanks to Mushfiqur Rahman for helping. Code below.

#include<string>
using namespace std;
bool isNumber(string s)
{
    if (s.empty()) return false;
    if ((s[0] == '-' || s[0] == '+') && s.length() == 1)
        return false;
    
    for (int i = 1; i < s.length(); i++)
        if (isdigit(s[i]) == false)
            return false;
    
    return true;
}

int main(void)
{
    string s;
    s="-1b34ggg--54-7-t--";
    string temp="";
    for(int i=0;i<s.length();i++)
    {
        if(isdigit(s[i]))
        {
            temp+=s[i];
        }
        else if(s[i]=='-')
        {
            
            if(isNumber(temp))
            {
                cout<<atoi(temp.c_str())<<" ";
                temp="";
                temp+=s[i];
            }
            else
            {
                temp="";
                temp+=s[i];
            }
        }
        else
        {
             if(isNumber(temp))
             {
                cout<<atoi(temp.c_str())<<" ";
             }
             temp="";
        }
    }
    return 0;
}