she*_*ets -1 c++ string static input
我是静态类型 C++ 的新手。在 JavaScript 中,我可以先检查数据类型,但这似乎非常复杂,而且答案似乎都暗示您没有“了解”该语言。
这是我用来测试 rand() 的代码,在那里我遇到了将字符串转换为整数的问题:
int main(){
std::string input;
cout <<endl<< "What to do?"<<endl;
cin >> input;
if (input == "rand")
{
cout << "what is the max?" << endl;
cin >> input;
int number;
if (stoi(input) > 1) {
number = stoi(input);
}
else {
number = 10;
cout << "using 10"<<endl;
}
cout << rand() % stoi(input);
return main();
}
}
Run Code Online (Sandbox Code Playgroud)
所以在 Javascript 中,我只会检查输入或结果的类型,但是人们在 C++ 中做什么?
不允许在评论中说谢谢,所以我在这里说谢谢!
好吧,让我们试试会发生什么:https : //godbolt.org/z/1zahbW
如您所见,std::stoi如果传递无效输入或其输入超出范围,则会引发异常。
但是,您应该意识到这std::cin >> some_string;有点不明显,因为它读取的是第一个“单词”,而不是一行或类似的东西,并且std::stoi(再次)执行相同的操作。
执行检查的一种方法可能是这样的:
#include <string>
#include <iostream>
int main(){
std::cout << "Please give me a number: " << std::flush;
std::string input;
std::getline(std::cin, input);
try {
auto value = std::stoi(input);
std::cout << "Thanks for the " << value << " (but the string was \"" << input << "\")\n";
} catch(std::invalid_argument const&) {
std::cout << "The provided value is not an integer\n";
} catch(std::out_of_range const&) {
std::cout << "The provided value is out of range\n";
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这将解析" 42 xyz"为42. 如果这对您的用例来说是个问题,您可能希望std::strtoi直接使用,或者在解析之前检查您的输入是否有效(例如,使用regex)
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |