求助:用C++编程,它用一个char数组和循环每次读取一个单词,到输入done为止.随后程序指出输入多少单词.

来源:百度知道 编辑:UC知道 时间:2024/06/22 02:07:21
例如 输入 ni hao ma da jia hao done wo hen hao
最后输出的结果是 6

// 不应用cstring,很容易出问题。题目出得不好

#include <iostream>
#include <string>

using namespace std;

int main()
{
string s;
int count = 0;
while(cin >> s && s != "done")
++count;

cout << count;

return 0;

}

// 实在要用C风格的串,为安全起见,写成这样比较好
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
ios::sync_with_stdio(true); // 保证两种风格的输入输出同步,在此不必需
const int Bufsize = 256;
char s[Bufsize];
char fmt[16];
sprintf(fmt, "%%%ds", Bufsize); // 初始化限制读入串长的格式串
int count = 0;
while(scanf(fmt, s) != 0 && strcmp(s, "done") != 0)
++count;

cout << count;

return 0;
}

int i=0;
char str[81];
for(;;)
{
fscanf("%s",str);
if(strcmp(str,"done"