My problem here is I don\'t know how to insert a rule wherein if a user inputted a number on the string, it will cout
a warning saying it\'s not valid, same wit
cin
sets a failbit when it gets input of an invalid type.
int x;
cin >> x;
if (!cin) {
// input was not an integer
}
You can also use cin.fail()
to check if the input was valid:
if (cin.fail()) {
// input was not valid
}
cout << "\n Enter number : ";
cin >> ch;
while (!cin) {
cout << "\n ERROR, enter a number" ;
cin.clear();
cin.ignore(256,'\n');
cin >> ch;
}
Use the .fail()
method of the stream. Something like below:-
cin >> aString;
std::stringstream ss;
ss << aString;
int n;
ss >> n;
if (!ss.fail()) {
// int;
} else {
// not int;
}
you could use cin.fail()
method! When cin
fails it will be true
and you could us a while
loop to loop until the cin
is true
:
cin>>d;
while(cin.fail()) {
cout << "Error: Enter an integer number!"<<endl;
cin.clear();
cin.ignore(256,'\n');
cin >> d;
}
//this program really work in DEV c++
#include <iostream>
using namespace std;
int main()
{
char input;
cout<<"enter number or value to check"<<endl;
cin>>input;
for(char i='a';i<='z';i++)
{
if(input==i)
{
cout<<"character"<<endl;
exit(0);
}
}
for(int i=0;i<=1000;i++)
{
if(input==i)
{
cout<<"number"<<endl;
}
}
}
How about something like this:
std::string str;
std::cin >> str;
if (std::find_if(str.begin(), str.end(), std::isdigit) != str.end())
{
std::cout << "No digits allowed in name\n";
}
The above code loops through the whole string, calling std::isdigit for each character. If the std::isdigit
function returns true for any character, meaning it's a digit, then std::find_if returns an iterator to that place in the string where it was found. If no digits were found then the end
iterator is returned. This way we can see if there was any digits in the string or not.
The C++11 standard also introduced new algorithm functions that can be used, but which basically does the above. The one that could be used instead is std::any_of:
if (std::any_of(str.begin(), str.end(), std::isdigit))
{
std::cout << "No digits allowed in name\n";
}