2020-02-10读取一行字符串

C++风格:

#include
#include
#include
//输入任意行,统计行数和总字符个数
using namespace std;
int main(void){
	int count = 0;
	int lenth = 0;
	string line;
	cout << "请输入任意行信息:" << endl;
	while(1){
		if(getline(cin,line) == NULL)//C++中读取一行,遇到文件结束符,同样是返回0,即NULL。
			break;
		count++;
		lenth += line.length ();
	}
	cout << "你共输入了:" << count <<"行" << endl;
	cout << "共计:" << lenth <<"个字符(包括空白字符)" << endl;
	
	system("pause");
	return 0;
}

C语言风格:(在前基础上稍作更改)


```cpp
#include
#include
#include
//输入任意行,统计行数和总字符个数
//using namespace std;
int main(void){
	int count = 0;
	int lenth = 0;
	char line[128] = {0};
	printf("请输入任意行信息:\n");
	while(1){
		if(fgets(line,sizeof(line),stdin) == NULL)//C++中读取一行,遇到文件结束符,同样是返回0,即NULL。//get(line)效果也一样
			break;
		count++;
		lenth += strlen(line);
	}
	printf("你输入了:%d行\n",count);
	printf("共计%d个字符(包括空白字符)\n",lenth);
	
	system("pause");
	return 0;
}

总结:
1. c++读取一行用getline(), C读取一行用gets,返回值是什么忘了就查手册。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值