标签:ring 缓冲区 -- 一个 交换 制表符 运算 使用 解决
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);
cin >> namel;
#include <iostream>
#include <string>
using namespace std;
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
所以说虽然可以使用 cin 和 >> 运算符来输入字符串,但它可能会导致一些需要注意的问题:当 cin 读取数据时,它会传递并忽略任何前导白色空格字符(空格、制表符或换行符)。一旦它接触到第一个非空格字符即开始阅读,当它读取到下一个空白字符时,它将停止读取
而在这个示例中,我们根本没有机会输入 city 城市名。因为在第一个输入语句中,当 cin 读取到 John 和 Doe 之间的空格时,它就会停止阅读,只存储John作为name的值。在第二个输入语句中,cin使用键盘缓冲区中找到的剩余字符,并存储 Doe 作为 city 的值。
getline(cin, inputLine);
#include <iostream>
#include <string>
using namespace std;
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
Orz。。。
标签:ring 缓冲区 -- 一个 交换 制表符 运算 使用 解决
原文地址:https://www.cnblogs.com/orange-233/p/12001099.html