Search code examples
c++stringcin

C++: Why does cin allow ints for inputs of strings?


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.


Solution

  • 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.