私は、ファイルを読み取って行数を数え、同時にその中の単語を数えることになっている課題に取り組んでいます。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;
}