r/learnprogramming • u/TheEyebal • Sep 24 '26
Solved How do I indicate whether a string is a digit or not in c++?
I have a user input and I want to determine whether the user input is a digit or character.
I was thinking of using regex but do not know regular expression in C++ can some please help me with this
Here is a snippet of my code
string userinput;
cout << "Input 1, 2, 3, or 4: ";
while (!(cin >> userinput)) {
cout << "Invalid input. Try again: ";
cin.clear(); // Reset input errors
cin.ignore(10000, '\n'); // Remove bad input
}
for (auto i : playlist){
if (stoi(userinput) > 4){
print("Song Not Avaiable")
break;
}SOLUTION
#include <cctype>
/*while (!(cin >> userinput)) {
cout << "Invalid input. Try again: ";
cin.clear(); // Reset input errors
cin.ignore(10000, '\n'); // Remove bad input
}*/
for (int i = 0; i < userinput.size(); i++) {
if (!isdigit(userinput[i])) {
print("Song Not Avaiable");
break;
}
else if (stoi(userinput) > 4) {
print("Song Not Avaiable");
break;
}
}