I'm working on a school project that requires the verification of a string for the input, and NOTHING ELSE. However, whenever I pass an int for bug testing (I.E. 0), the program doesn't trigger cin.fail(). For example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string lastName;
cin >> lastName;
if (cin.fail()) {
cout << "INT";
}
else {
cout << "STRING";
}
return 0;
}
INPUT: 1999
OUTPUT: STRING
Why is this the case? I created a personal project using this exact same same structure and had no problems there but can't get it to work properly here.
CodePudding user response:
A string is a sequence of characters. Therefore, 1999
is a valid string.
If you want to verify that the string consists only of alphabetical characters and does not contain any digits, you can use the function std::isalpha
on every single character in the string:
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string lastName;
std::cin >> lastName;
if ( std::cin.fail())
{
std::cout << "Input failure!\n";
return 0;
}
for ( char c : lastName )
{
if ( !std::isalpha( static_cast<unsigned char>(c) ) )
{
std::cout << "String is invalid!\n";
return 0;
}
}
std::cout << "String is valid!\n";
return 0;
}
Note however that in the default locale, std::isalpha
will only consider the standard letters 'A'
to 'Z'
and 'a'
to 'z'
as valid letters, but not letters such as ê
and ä
. Therefore, you may have to change the locale if you are dealing with non-English characters.
CodePudding user response:
That is because the program think the data you input is a string. Why not change it? int a
, then cin>>a
. If cin.fail()
is true, it's a string. If it's false, it's an integer.
#include <iostream>
#include <string>
using namespace std;
int main() {
int lastName;
cin >> lastName;
if (cin.fail()) {
cout << "STRING";
}
else {
cout << "INT";
}
return 0;
}
CodePudding user response:
int 0
is just 0x00 0x00 0x00 0x00
which is a string of bytes. All types are a string of bytes. It's how those bytes are interpreted that matters. So if cin
expects a byte string and you hand it 0x00 0x00 0x00 0x00
it will treat it like text.
Inversely, "jump"
is 0x6a 0x75 0x6d 0x70
which interpreted as a 4-byte integer int
is 1786080624
.