How to check whether a user enters a number or a word in C++

1 Answer

0 votes
#include <iostream>
#include <cctype> 

int main() {
    std::cout << "Please enter a number or a word: ";
    std::cout.flush(); // clear the input stream (cin) as preparation for the next input 

    std::cin >> std::ws; // skip the leading whitespace include newline
    int ch = std::cin.peek(); // retrieve the next character from the stream without consuming it

    if (ch == EOF) {
        return 1;
    }

    if (std::isdigit(ch)) {
        int n;
        std::cin >> n;
        std::cout << "You entered the number: " << n << '\n';
    } else {
        std::string str;
        std::cin >> str;
        std::cout << "You entered the word: " << str << '\n';
    }
}
  
  
 
/*
run1:
 
Please enter a number or a word: 324534
You entered the number: 324534


run2:
 
Please enter a number or a word: c++
You entered the word: c++

*/

 



answered Nov 22, 2024 by avibootz
edited Nov 22, 2024 by avibootz
...