首页 > 试题广场 >

编写一个满足下述练习中描述的程序,但使用string对象而不

[问答题]
编写一个满足下述练习中描述的程序,但使用string对象而不是字符数组。请在程序中包含头文件string,并使用关系运算符来进行比较测试。
它使用一个char数组和循环来每次读取一个单词,直到用户输入done为止。随后,该程序指出用户输入了多少个单词(不包括done在内)。下面是该程序的运行情况:

Enter words (to stop, type the word done):
anteater birthday category dumpster
envy finagle feometry done for sure
You entered a total of 7 words.

#include<iostream>
#include<string>
using namespace std;
int main()
{
 string s;
 int sum = 0,i = 0;
 cout << "Enter words(to stop,type the word done):\n";
 cin >> s;
 while(1)
 {
  i = 0;
  if (s[i] == 'd' && s[i + 1] == 'o' &&
   s[i + 2] == 'n' && s[i + 3] == 'e' && s.length() == 4) {
   break;
  }
  sum++;
  cin >> s;
 } 
 cout << "Your entered a total of " << sum << " words." << endl;
   return 0;
}
发表于 2020-10-18 14:57:13 回复(0)