有很多方法可以做到這一點,一個是簡單地閱讀它作爲一個字符串,並嘗試分析它在自己的代碼的整數。如果解析成功,那麼你有一個整數,否則你有一個字符串。
有解析字符串,其中包括幾個方面(但不限於):
簡單的例子使用std::stoi
:
std::string input;
if (std::getline(std::cin, input))
{
try
{
std::size_t pos;
int n = std::stoi(input, &pos);
// Input begins with a number, but may contain other data as well
if (pos < input.length())
{
// Not all input was a number, contains some non-digit
// characters as position `pos`
}
else
{
// Input was a number
}
}
catch (std::invalid_argument&)
{
// Input is not a number, treat it as a string
}
catch (std::out_of_range&)
{
// Input is a number, but it's to big and overflows
}
}
如果你不想使用異常,那麼舊的C函數std::strtol
可以用來代替:
std::string input;
if (std::getline(std::cin, input))
{
char* end = nullptr;
long n = std::strtol(input.c_str(), &end, 10);
if (n == LONG_MAX && errno == ERANGE)
{
// Input contains a number, but it's to big and owerflows
}
else if (end == input.c_str())
{
// Input not a number, treat as string
}
else if (end == input.c_str() + input.length())
{
// The input is a number
}
else
{
// Input begins with a number, but also contains some
// non-number characters
}
}
你是什麼意思的「第一價值」?例如,如果該文件讀取「foo.123」,是「foo.123」的第一個值?或者是「foo」。第一個和「123」第二個?或者是什麼?你需要以足夠的精度指定你想要的東西,否則唯一有用的答案就是「實現你想要的任何東西」。 –
首先是foo,然後是123這樣:edd 123 fed 1 dwd。我想看看哪些是字符串,哪些是int。 – SaladSnake
所以你想閱讀一系列由空白分隔的字符串,並看看它們中的哪些僅由數字組成? –