c++中getline函数对换行符的处理

题目:https://blog.csdn.net/tigerisland45/article/details/51747138

C - 字符串统计

对于给定的一个字符串,统计其中数字字符出现的次数。

Input

输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一个由字母和数字组成的字符串。 

Output 

对于每个测试实例,输出该串中数值的个数,每个输出占一行。 

Sample Input

2
asdfasdf123123asdfasdf
asdf111111111asdfasdfasdf

Sample Output

6
9

 老师的程序:

/* HDU2017 字符串统计 */
 
#include <stdio.h>
 
#define MAXSIZE 4096
 
int main(void)
{
    int n, count;
    char s[MAXSIZE], *t;
 
    scanf("%d", &n);
    while(n--) {
        // 计数清零
        count = 0;
 
        // 读入字符串
        scanf("%s", s);
 
        // 统计数字字符个数
        t = s;
        while(*t) {
            if('0' <= *t && *t <= '9')
                count++;
            t++;
        }
 
        // 输出结果
        printf("%d\n", count);
    }
 
    return 0;

这程序挺好的,我写的时候用的是C++

//编译环境为GCC
//getline使用的时候不需要考虑/n的问题 
#include<iostream>
#include<string>
#include<ctype.h>
using namespace std;

int main()
{
	int i,n,length,count;
	string s;
	while(cin>>n)
	{
		getchar();
		while(n--)
		{
			i=0;
			count=0;
			getline(cin,s);//getline不会接收换行符,舍弃,注意是舍弃/n 
			//getchar();//接收回车 ,灰常重要 
			//gets(s);//会把最后的回车换成/0 
			length=s.length();//下次getline的输入 
			while(length--)
			{
				if(isdigit(s[i++]))
					count++;
			}
			cout<<count<<endl;
		}
	} 
	return 0;
} 

写程序的时候遇到回车符,与getlien()的问题。

实验的结果是,getline()会读取缓存区的换行符导致直接换行。

所以,getline()函数之前的换行符,要用getchar()吸收。

geiline()函数之后的换行符会被读取,并换行,即不用考虑。

猜你喜欢

转载自blog.csdn.net/sinat_38816924/article/details/82491519