[英]How do I check if input is an integer/string?
我在這里的問題是,我不知道如何插入一個規則,其中,如果用戶在輸入串數字,它會cout
警告說這是不是有效的,具有相同如果用戶輸入的上檔次的字符串/字符。 如何? 我一直在嘗試,但公式不起作用。
int x, cstotal = 100, extotal = 150;
double scorecs, exscore, labtotala, labtotalb, total;
string mystr = "";
cout << "Compute for: " << "\n" << "1. Laboratory Grade " << "\n" << "2. Lecture Grade" << "\n" << "3. Exit" << "\n";
cout << "Please enter a number: ";
cin >> x;
switch (x) {
case 1:
cout << "Compute for laboratory grade." << "\n";
cout << "Enter Student Name: ";
cin >> mystr;
cout << "Good day, " << mystr << " . Please provide the following grades: " << "\n";
cout << "CS Score: ";
cin >> scorecs;
cout << "Exam Score: ";
cin >> exscore;
labtotala = scorecs / cstotal * 0.6;
labtotalb = exscore / extotal * 0.4;
total = labtotala + labtotalb;
cout << "Your Laboratory Grade is " << total * 100 << "\n";
system("pause");
break;
case 2:
cout << "Compute for lecture grade." << "\n";
cout << "Enter Student Name: ";
cin >> mystr;
cout << "Good day, " << mystr << " . Please provide the following grades: " << "\n";
cout << "CS Score: ";
cin >> scorecs;
cout << "Exam Score: ";
cin >> exscore;
labtotala = scorecs / cstotal * 0.7;
labtotalb = exscore / extotal * 0.3;
total = labtotala + labtotalb;
cout << "Your Lecture Grade is " << total * 100 << "\n";
system("pause");
break;
cin
在獲得無效類型的輸入時設置failbit
。
int x;
cin >> x;
if (!cin) {
// input was not an integer
}
您還可以使用cin.fail()
來檢查輸入是否有效:
if (cin.fail()) {
// input was not valid
}
這樣的事情怎么樣:
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";
}
上面的代碼遍歷整個字符串,為每個字符調用std::isdigit
。 如果std::isdigit
函數對任何字符返回 true,這意味着它是一個數字,則std::find_if
返回一個迭代器,指向字符串中找到它的那個位置。 如果沒有找到數字,則返回end
迭代器。 這樣我們就可以查看字符串中是否有任何數字。
C++11 標准還引入了可以使用的新算法函數,但基本上完成了上述工作。 可以使用的一個是std::any_of
:
if (std::any_of(str.begin(), str.end(), std::isdigit))
{
std::cout << "No digits allowed in name\n";
}
cout << "\n Enter number : ";
cin >> ch;
while (!cin) {
cout << "\n ERROR, enter a number" ;
cin.clear();
cin.ignore(256,'\n');
cin >> ch;
}
使用流的.fail()
方法。 類似於以下內容:-
cin >> aString;
std::stringstream ss;
ss << aString;
int n;
ss >> n;
if (!ss.fail()) {
// int;
} else {
// not int;
}
你可以使用cin.fail()
方法! 當cin
失敗時,它將為true
,您可以使用while
循環進行循環,直到cin
為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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.