c++读一行数字以换行结束,读一行句子以换行结束,读多行字符串

基础

1、getchar()

头文件#include<cstdio>
从标准输入读下一个字符。原返回int(如输入a,函数返回97)。

2、getline()

读入一行字符串,以换行结束。

应用:实现输入

1、读一行整数,以换行结束。便输出。

输入: 10 20 30 80 70
输出: 10 20 30 80 70

#include <iostream>
#include <cstdio> 
#include <vector>
using namespace std;

int main(){
	int num;
	vector<int> v;
	while(cin>>num){
		v.push_back(num);
		char ch= gerchar();//读取下一个字符,为换行符,则break
		if(ch=='\n')
			break;
	}
	//输出略。
	return 0;
}

2、读一行句子以换行结束

	string words;
    getline(cin, words);//读入一行字符串,遇到换行结束
    cout<< words<<endl;

3、读多行字符串

假如读一组字符串。注意用while(getline(cin, str))要写上if(str.size()==0) break;才能结束循环。
输入:
li xiao ming
gao yang
chen chen
liu wen

#include <iostream>
#include <cstdio> 
#include <vector>
using namespace std;

int main(){
	string str;
	vector<string> str_list;
	while(getline(cin, str){
		if(str.size()==0)    break;//记得要这句,才能结束输入
		str_list.push_back(str);
	}
	cout<< str_list.size()<<endl; 
	for(auto s: str_list){
		cout<< s << endl;
	}
	return 0;
}

输出:
4
li xiao ming
gao yang
chen chen
liu wen

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值