Only Read Numbers in a string

Im trying to only show the numbers in a string from user input.
Right now i cannot get it to cout anything. Help please. Here is the code .


#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
char string[80];
char num[80];
scanf("%s", string);

int i = 0;
int j = 0;
cout << i << endl;
while(string[i] != '\0')
{
if(string[i] >= '0' && string[i] <= '9')
{
num[j] = string[i];
j++;
}
i++;
}
num[j] = '\0';
int inputval = atoi(num);
return 0;
}
closed account (zb0S216C)
Quite simple, really:

1
2
3
4
bool Is_Number( const char &Value )
{
    return( ( Value >= '0' ) && ( Value <= '9' ) );
}

This code takes a character as an argument. It then evaluates the value of Value. If Value is between the ASCII character equivalent of 0 (zero) and 9, the function returns true; false otherwise. You can invoke this function like this:

1
2
3
4
5
6
char String[7] = "Wa22ak";

if( Is_Number( String[2] ) )
    std::cout << "Is a number\n";

else std::cout << "Isn't a number\n";


Wazzak
Last edited on
It looks like its working, just print out the value of inputval.
1
2
3
4
num[j] = '\0';
int inputval = atoi(num);
cout << "Just nums: " << inputval << endl;
return 0;
$ ./a.out
test1234this5678
0
Just nums: 12345678
Topic archived. No new replies allowed.