C++getline输入

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值