下面是两种方式的实现,部分代码:
C style strcmp函数:
const int STR_LIM = 50;
int n = 0;
char word[STR_LIM];
cout << "Enter words (to stop, type the word \"done\"):\n";
while (cin >> word && strcmp(word, "done"))
{
++n;
};
cout << "You entered " << n << " words." << endl;C++ class:
int n = 0;
string word;
cout << "Enter words (to stop, type the word \"done\"):\n";
while (cin >> word && (word != "done"))
{
++n;
};
cout << "You entered " << n << " words." << endl;当使用class 时不能使用strcmp函数,因为strcmp函数定义的是两个字符串比较,否则会报错。
本文对比了C++类和C风格字符串在计数输入字符串数量时的不同实现方法,包括如何通过循环和条件判断终止输入,并在结束时输出输入的字符串数量。
1502

被折叠的 条评论
为什么被折叠?



