我正在进行一项任务,我应该读取一个文件并计算行数,同时计算其中的单词.我在while循环中尝试了getline和strtok的组合,但是没有用.
file:example.txt(要读取的文件).
嗨,你好,这真是一个惊喜.
欢迎来到这个地方.
愿你在这里过得愉快.
(3行,有些话).
Readfile.cpp
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
int main()
{
ifstream in("example.txt");
int count = 0;
if(!in)
{
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
string tok;
char * t2;
while(in)
{
in.getline(str, 255);
in>>tok;
char *dup = strdup(tok.c_str());
do
{
t2 = strtok(dup," ");
}while(t2 != NULL);
cout<<t2<<endl;
free (dup);
count++;
}
in.close();
cout<<count;
return 0;
}
Run Code Online (Sandbox Code Playgroud)