首页 > 编程语言 > 详细

C++ 字符串读取getline函数

时间:2019-08-22 00:41:05      阅读:156      评论:0      收藏:0      [点我收藏+]
官方说明:
(1)    
istream&getline(istream&isstring&str,char delim);
istream&getline(istream && isstring&str,char delim);
(2)    
istream&getline(istream&isstring&str);
istream&getline(istream && isstring&str);

从流中获取行字符串
从is中提取字符并将它们存储到str中,直到找到分隔字符delim(或换行符,(2)中默认为\ n)。

is:
istream object from which characters are extracted.
str:
string object where the extracted line is stored.
The contents in the string before the call (if any) are discarded and replaced by the extracted line.

例如:

第一行输入一个n,代表接下来输入n行字符串(每行字符串可以包含空格)

3
aa aa
bbb
ccc
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<string> vec;
    int n;
    cin >> n;
    cin.get();//由于输入n之后回车,使用这句回车符号吃掉,否则下面的getline()获取的第一个字符串为‘\n‘

    while(n--)
    {
        string s;
        getline(cin, s); //默认为回车符,若以其他符号为分隔符,改为getline(cin, s, ‘,‘),例如逗号
        vec.push_back(s);       
    }
    cout<< "result: " <<endl;
    for(int i=0; i<vec.size(); ++i)
    {
        cout << vec.at(i) << endl;
    }

    system("pause");
    return 0;
}

 

技术分享图片

若没有cin.getr()将 ‘\n‘ 吃掉,则会出现以下情况:

输入两次便不可在输入,输出结果中第一行为空(只有一个回车符号,所以显示为空)

技术分享图片


 

C++ 字符串读取getline函数

原文:https://www.cnblogs.com/jodio/p/11391648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!