(C++)输入一段完整的英文语句,统计其英文单词个数,并将个数保存到文件file.txt中
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
//输入一段完整的英文语句,统计其英文单词个数,并将个数保存到文件file.txt中
int main()
{
char strword[1024];
gets_s(strword, 1024);
//第二种输入方法:cin.getline(strword, 1024);
int count = 0;
for (int i = 0; i < strlen(strword); i++) {
if (strword[i] == ' ') {
count++;
}
}
cout << count+1 << endl;
ofstream outfile("file.txt");
if (!outfile) {
cerr << "open file.txt error" << endl;
exit(1);
}
outfile << count+1 << endl;
outfile.close();
return 0;
}