c++统计单词数,在switch中输入字符串时的问题


在写统计单词个数时发现了一个问题,单独运行是没问题的,但是放在switch中,它会直接“跳过”我从键盘上输入字符的步骤。如图:
 

#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

void countword()
{
	char str[100];
	cout << "输入一句英文:" << endl;
	int i = 0;
	int word = 1;
	cin.getline(str, 100);
	
	while (str[i] != '\0') {
		if (str[i] == ' ') {
			word++;
		}
		i++;
	}
	if (str[0] == '\0') {
		word--;
	}
	cout << "单词个数为" << word << endl;
	return;


}
int main()
{	
	int start = 0;
	cin >> start;
	switch (start)
	{
	case 1:
		countword();
		break;
	};
	return 0;
}

在试了几种输入方式之后,我觉得这应该是缓存区中有残留字符,于是想cin.get()先舍弃一波。

cin.get(无参数)没有参数主要是用于舍弃输入流中的不需要的字符,或者舍弃回车,弥补cin.get(字符数组名,接收字符数目)的不足.

如图:

void countword()
{
	char str[100];
	cout << "输入一句英文:" << endl;
	int i = 0;
	int word = 1;
	cin.get();
	cin.getline(str, 100);
	
	while (str[i] != '\0') {
		if (str[i] == ' ') {
			word++;
		}
		i++;
	}
	if (str[0] == '\0') {
		word--;
	}
	cout << "单词个数为" << word << endl;
	return;


}

可以看到,这个方法是可行的。

然后我又想试试这个函数

函数名: fflush

功 能: 清除读写缓冲区,需要立即把输出缓冲区的数据进行物理写入时

头文件:stdio.h

原型:int fflush(FILE *stream)

其中stream是要冲洗的流

fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃[非标准],一般用不到。

fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上

printf("字符串");后面加fflush(stdout);可提高打印效率!

结果不行,唉。为什么呢?

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

樱桃兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值