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

Roc*_*one 7 c++ string parsing token

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

Roc*_*one 5

刚刚做对了!! 刚删除所有不必要的代码.

int main()
{    
    ifstream in("example.txt");
    int LineCount = 0;
    char* str = new char[500];

    while(in)
    {
        LineCount++;
        in.getline(str, 255);
        char * tempPtr = strtok(str," ");
        while(tempPtr)
        {
            AddWord(tempPtr, LineCount);
            tempPtr = strtok(NULL," ,.");
        }
    }
    in.close();
    delete [] str;
    cout<<"Total No of lines:"<<LineCount<<endl;
    showData();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

BTW原始问题陈述是创建一个索引程序,它将接受用户文件并创建所有单词的行索引.


Ree*_*sey 0

尝试将您的 cout<<t2<<end;语句移至 while 循环中。

这应该使您的代码基本正常运行。

您可能想查看这篇类似的文章以了解其他方法。