第二天打卡第二个问题

发布时间 2023-04-13 18:23:44作者: 序章0

问题描述:

编写一个程序,它使用一个char数组和循环来每次读取一个单词,直到用户输入done为止。随后,该程序指出用户输入了多少个单词不包括done在内。下面是运行状况

enter words:

anteater birthday category dumpster

envy finagle geometry done for sure

you entered a total of 7 words

要求程序中包含cstring,并使用函数strcmp()来进行比较测试。

解决思路:1.建立一个char数组用于存储单词,定义一个初始化为0的变量记录1循环次数

2.循环输入单词存储到char数组当中,每循环一次,变量就加一

3.判断单词是否和done一样,一样就跳出循环

4.输出变量。

代码:

#include <iostream>
#include<cstring>
using namespace std;
int main()

{
char a[46];
char b[5] = "done" ;
int ans = 0;
cout << "enter words:";
cout << endl;
for (;;)
{
cin >> a;
if (strcmp(a, b) == 0)
break;
ans++;
}
cout << "you entered a total of ";
cout << ans;
cout << " words";
return 0;
}