cin读取用户输入时,它会传递并忽略任何前导白色空格字符(空格、制表符、换行符),一旦它接触到第一个非空格字符开始阅读,读到下一个空白字符时,它停止读取,剩下的输入的存在缓冲区。
int main()
{
string name;
string city;
cout << "Please enter your name: ";
cin >> name;
cout << "Enter the city you live in: ";
cin >> city;
cout << "Hello, " << name << endl;
cout << "You live in " << city << endl;
return 0;
}
输入输出:
Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe
没机会输入第二个city城市名,因为在第一个输入语句中,当cin读到John Doe之间的空格时,会自动停止阅读。只存储John作为name的值,在第二个输入语句红,cin使用键盘缓冲区找到剩余字符,并存储John作为city的值
getline函数:读取整行,包括含有空格的字符串
//getline(cin, inputLine);
int main()
{
string name;
string city;
cout << "Please enter your name: ";
getline(cin, name);
cout << "Enter the city you live in: ";
getline(cin, city);
cout << "Hello, " << name << endl;
cout << "You live in " << city << endl;
return 0;
}
输入输出:
Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago
同时使用getline还可以实现split的功能
getline(input, str, delim);
参数:
input - 流中获取数据,istringstream iss
str - 把数据转换成字符串放入str中
delim - 分隔符,默认的分隔符是’\n’字符,也可以自定义
string line = "a,c,bb";
vector<string> vec;
istringstream iss(line);
string temp;
while(getline(iss,temp,',')){
vec.push_back(temp);
}
//最后vec中存储的结果时"a"、"c"、”bb“
转载引用自:http://c.biancheng.net/view/1345.html