求帮忙写一小段C++代码

来源:百度知道 编辑:UC知道 时间:2024/04/29 03:20:51
用C++ 写一个段代码 包含int main(int argc, char** argv),作用是从一个文件(比如Hamlet.txt)中读取词组然后输出文件中有多少个单词(全部为英文单词 以空格为区分 标点符号算一个单词)。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int num0=0;
int num1=0;
int tempernum0=0;
int line=0;
int i;
string str;//不可以用char定义。
string filename;
fstream file;
cout<<"please input the filename:";
cin>>filename;
file.open(filename.c_str());//例如输入的是 D:\Hamlet.txt
if(!file)
{
cout<<"file open fail"<<endl;
}
cout<<"文本中的内容是:"<<endl;
while(getline(file, str, '\n'))
{
cout<<str<<endl;//文本输出
line++;//行数统计
int n=str.length();
if(n!=0)
tempernum0++;//统计非空行末尾的单词数目
string::iterator itr=str.begin();
for(i=0;i<n-1;i++)
{
if(itr[i]==' '&&itr[i+1]!=' ')
num0++;//字数统计