輸入一行字符串,統計單詞個數。單詞由字母數字組成,以空格分隔(連續空格視為一個分隔符,行首空格不計)。
in_word:當前是否在單詞內in_word = false!in_word:新單詞開始,count++,in_word = true#include <cstdio>
#include <cstring>
int main() {
char line[1000];
fgets(line, sizeof(line), stdin);
// 移除可能的換行符
line[strcspn(line, "\n")] = '\0';
int count = 0;
bool in_word = false;
for (char *p = line; *p; ++p) {
if (*p == ' ') {
in_word = false;
} else if (!in_word) {
in_word = true;
++count;
}
}
printf("There are %d words in this line.\n", count);
return 0;
}
fgets 讀整行含空格#include <iostream>
#include <string>
using namespace std;
int main() {
string s; getline(cin, s);
int cnt = 0; bool in = false;
for (char c : s) {
if (c == ' ') in = false;
else if (!in) { in = true; ++cnt; }
}
cout << "There are " << cnt << " words in this line." << endl;
}