小编Roc*_*one的帖子

如何将文本文件拆分成文字?

我正在进行一项任务,我应该读取一个文件并计算行数,同时计算其中的单词.我在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)

c++ string parsing token

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×1

parsing ×1

string ×1

token ×1