读入——getline()函数和cin

  1. 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

  1. 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 your
why
is
why
why
your
why

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值