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;
}