cin, getline, get 使用小结

参考https://www.cnblogs.com/dj0325/p/8513356.html
  1. cin()可以读数字,字符,字符串,cin使用空白(空格、制表符和换行符)来确定字符串结束的位置,并且对于换行符,cin会把换行符留在输入队列。cin读取字符串放到数组中,并自动在结尾添加空字符。
  2. getline 读取一行字符串,直到到达换行符,随后getline将丢弃换行符。
  3. cin.get(str,num)
    读取一行字符串,直到到达换行符,将换行符保留到输入序列中。
    cin.get(char) 读取一个字符
    cin.get(ch)读取输入中的下一个字符(包括空格和换行符),但输入仍被缓冲。
    cin.get() 读取缓冲区的一个字符,返回值为char。
#include <string>
#include <iostream>
using namespace std;
int main(){
    int a;
    cin>>a;
    cout<<"0:"<<a<<endl;

    string str;
    getline(cin,str); //此处会将 换行符读入,并舍弃
    cout<<"1:"<<str<<endl;
    
    getline(cin,str);
    cout<<"2:"<<str;
    return 0;
/*输入
1
123,45
1234,54
输出
[in]1
[out]0:1
[out]1:
[in]123,45
[out]2:123,45
}
#include <string>
#include <iostream>
using namespace std;
int main(){
    int a;
    cin>>a;
    cout<<"0:"<<a<<endl;

    string str;
    /**针对下一行特性,可以在getline()前加一行代码,读回车**/
    get();
    getline(cin,str); //此处会将 换行符读入,并舍弃
    cout<<"1:"<<str<<endl;
    
    getline(cin,str);
    cout<<"2:"<<str;
    return 0;
/*
[in]1
[out]0:1
[in]123456
[out]1:123456
[in]123456678,mm
[out]2:123456678,mm
*/

对于连续的一行字符串可以直接用 cin 读入,更方便

#include <string>
#include <iostream>
using namespace std;
int main(){
    int a;
    cin>>a;
    cout<<"0:"<<a<<endl;

    string str;
    cin>>str;
    cout<<"1:"<<str<<endl;
    
    cin>>str;
    cout<<"2:"<<str;
    return 0;
}
/*
[in]112
[out]0:112
[in]1234dddd
[out]1:1234dddd
[in]3456788
[out]2:3456788
cin 会忽略空格和换行符
*/

也可以这样读

int main(){
    int m;
    cin>>m;
    
    char c;
    string str;
    while(cin>>c){
        str += c;
    }
    cout<<str<<endl;
    return 0;
}
/*【in】
5
1,2,3,4
【out】
1,2,3,4

存在情况
[in]
5
1,2,3,4
gfgdgd
[out]
1,2,3,4gfgdgd
因为 cin 会忽略空格和换行符
*/

对于间断的字符串,若想读取一行,用getline()

#include <string>
#include <iostream>
using namespace std;
int main(){
    string str;
    cin>>str;
    cout<<str<<endl;
    return 0;
}
//[in]111 222 333 fff ggg
//[out]111
#include <string>
#include <iostream>
using namespace std;
int main(){
    string str;
    getline(cin,str);
    cout<<str<<endl;
    return 0;
}
//[in]111 222 333 fff ggg
//[out]111 222 333 fff ggg
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值