我想知道在 C++ 中是否有一种方法可以像 C 语言一样同时采用两种不同类型的变量作为输入。 例如,我应该从用户读取一个命令(一个字符串),后跟一个索引(一个整数),它们之间用空格分隔。
最佳答案
std::istream
的 >>
运算符是 overloaded for many different types 。任何从 std::istream
继承 >>
的类都可以读取 >>
重载的所有类型的输入。这意味着您可以将 >>
运算符与 std::cin
、std::ifstream
、std::istringstream
一起使用code> 等以多种类型读取。
您的案例的基本语法将采用以下形式
std::string s;
int n;
std::cin >> s >> n; // or std::ifstream, etc.
当然,您应该执行错误检查以确保您确实收到了预期的结果。您可以使用 !
运算符来检查流是否处于良好状态。因此,根据您的情况,您可以使用以下内容:
std::string s;
int n;
if (!std::cin) {
// error handling here
} else {
std::cin >> s; // get the std::string
}
if (!std::cin) {
// error handling here
} else {
std::cin >> n; // get the int
}
关于c++ - 在 C++ 中立即读取由空格分隔的输入字符串和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25982101/