How to get only digits from an input string?
Hello friends,
I am first year computer science. In last lecture we get assignment on c++ program. In that assignment one program is there like
How to get only digits from an input string? I tried various method but none of them worked out. I want to ignore any blank spaces, dashes, or non-digit characters and I want only number. Please help me.
Re: How to get only digits from an input string?
Hey it is very simple program. You have to just use isdigit() function to get only digits from an input string. isdigit() function is used to check if character is decimal digit or not. Just try to understand following example. It is very simple program.
Code:
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char strs[]="17s76asd";
int years;
if (isdigit(strs[0]))
{
years = atoi (strs);
printf ("The year that followed %d was %d.\n",years,years+1);
}
return 0;
}
Re: How to get only digits from an input string?
It is very simple program. I have written following program for you. In the following program I have use isdigit or atoi function to get only digits from an input string. I have use <iostream> class to load input and output method.
Code:
#include <iostream>
#include <cctype>
#include <string>
#include <sstream>
using namespace std;
string EANs;
int eans;
int main()
{
cout<<"Enter an another world ";
cin>>EANs;
if (isdigit(EANs))
{
eans= atoi(EANs);
}
cout<<eans;
}
Re: How to get only digits from an input string?
It is very simple program. You have to just take each character from string and you have to check this value for numeric. I have written simple program for you. In this code I have use for loop to take each value from string and check with isdigit(test[k]) function.
Code:
#include <iostream>
using namespaces std;
int main()
{
string tests = "1547-3589-4834";
for(int k=0; k<test.length(); k++)
{
if(isdigit(test[k]))
cout<<test[k];
}
cin.ignore();
cin.get();
return 0;
}
Re: How to get only digits from an input string?
It is very simple program. You have to just use isdigit() function to check for digit. just pass the input string to this function and save the result in another string variable. I also have use iostream class to use input and output method.
Code:
#include <iostream>
#include <cctype>
#include <string>
#include <sstream>
using namespace std;
int main()
{
cout<<"Enter an another ";
cin>>EANs;
for(int numbers=0; number<EANs.length; numbesr++;)
{
if(isdigit(EAN[numbers]))
{
int x[numbers]=EANs[numbers];
}
}
cout<<xs0<<xs1<<xs2<<xs3<<xs4<<xs5<<xs6<<xs7<<xs8<<xs9<<xs10<<xs11<<xs12;
}