我想知道是否有一個特定的函數來檢查輸入是一個int還是一個字符。C++檢查一個int或char並返回一個文本
然後返回一個答案,如「這是一個整數」或「這是一個字符」。
如果沒有特定的轉換功能,我應該怎麼做呢?
在此先感謝!
我想知道是否有一個特定的函數來檢查輸入是一個int還是一個字符。C++檢查一個int或char並返回一個文本
然後返回一個答案,如「這是一個整數」或「這是一個字符」。
如果沒有特定的轉換功能,我應該怎麼做呢?
在此先感謝!
以字符串形式輸入。檢查字符串是由單個字符還是多個字符組成(僅限數字)。然而你認爲'2'是什麼?字符2或整數值2?
可以使用ISDIGIT函數來檢查輸入的字符是否是整數或不其中檢查位0 1 2 3 4 5 6 7 8 9 像:
#include<iostream>
using namespace std;
int main(){
char inp;
cin>>inp;
if(isdigit(inp))
cout<<"Integer";
else
cout<<"Character";
return 0;
}
這是我所做
#include<ctype.h>
str_int_check(char *a)//checks weather all elements of string are integers
{
int flag= 0;
for(int i = 0; a[i]; i++)
{
if(isdigit(a[i])) ;
else if (a[i]== '-' && i == 0);//in case of negative values
else
{
flag = -1;
break;
}
}
return flag; //returns 0 if all characters are digit, else returns 1
}
我寧願試試錯誤的方法:嘗試解析傳入的字符串作爲整數,檢查錯誤,如果是的話,傳遞的值不是整數。例如,strtol
具有十分便利的接口:
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <errno.h>
const char* the_answer(const char* str) {
char* end; // Pointer to first invalid character found by strtol
const char* endstr = str + std::strlen(str); // Last character in string
long val = strtol(str, &end, 10);
if(val == 0) {
// Not all characters were parsed, consider as characters
if(endstr != end)
return "This is an characters";
// This is valid, but too long integer to be kept in long type
if(errno == ERANGE)
return "This is an integer";
}
return "This is an integer";
}
其中給出這樣的:
0 This is an integer
20 This is an integer
-20 This is an integer
2000000000000000000000000000000000000000000000000000 This is an integer
0xABCD This is an characters
Hello, World This is an characters
附:從the_answer
返回字符串實際上是笑話,返回枚舉值或布爾值。
字符是整數。另外,一個數字整數可以用一個「char」來表示。你需要提供更多的細節。 –
您可以使用'std :: isdigit()'來檢查輸入的單個字符。 –
你需要在運行時做到這一點嗎?因爲在編譯時可以使用函數重載或模板來區分它們... – myaut