读入——getline()函数和cin

来源:互联网 发布:淘宝内衣模特偷拍网盘 编辑:程序博客网 时间:2024/06/05 20:40
    1.
#include <iostream>#include <string>using namespace std;int main(int argc, char const *argv[]){    string line;    cout<<"输入字符串,可包含空格:"<<endl;    //这里getline函数     while(getline(cin,line))    {        cout<<line<<endl;     }    return 0;}

输出结果:

输入字符串,可包含空格:what is your name?what is your name?

这里将空格字符也保存在line里面了。
这里的getline()函数返回值是istream对象,这里的getline()进行循环读取,每次读入一整行(即以换行符结尾),直至文件结束或遇到异常输入。

这里是对于getline()函数的详细解释。
https://zhidao.baidu.com/question/377613227.html

    2.
#include<iostream>#include<string>using namespace std;int main(){    string word;    string word1="why";    while(cin>>word)    {        cout<<word1<<endl;        cout<<word<<endl;        cout<<word1<<endl;     }    return 0;} 

这里采用cin进行读入,以下为输出结果

is yourwhyiswhywhyyourwhy

这里输入了一个“is your”的字符串,字符串中带有空格,循环体执行了两次,也就是说在缓冲区读到空格符后停止,然后进入循环体,之后再继续读取。单词中不会包含空格。

原创粉丝点击