2014-09-22 260 views
2

我想知道是否像在C中一样,在C++中有一种方法可以将两种不同类型的varibales作为输入。 例如我应该从用户读取一个命令(一个字符串)后跟一个索引(一个整数),然后用空格分隔。立即读取输入字符串和整数用C++中的空格分隔

+0

'字符串; INT B; CIN >> A >> B;' – Omid 2014-09-22 19:55:15

+0

我有一些答案收集[这里](http://stackoverflow.com/问题/ 23047052 /为什么 - 不读-A-结构记录字段从 - stdistream - 失败 - 和 - 如何灿的i-FI)。 – 2014-09-22 19:56:45

+0

这是如此接近于许多重复*从文件读取*我无法开始标记为重复的问题。请在发布之前搜索关键字(通常更快)。 – 2014-09-22 21:36:41

回答

2

对于std::istream>>运营商是overloaded for many different types。从std::istream继承>>的任何类都可以读取所有类型的输入>>被重载。这意味着您可以使用>>运算符与std::cin,std::ifstream,std::istringstream等以多种类型读取。

对你的情况的基本语法将有形式

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 
} 
相关问题