从输入文件逐行输入,并使用strtok()和输出到输出文件中进行tokenize [英] Input line by line from an input file and tokenize using strtok() and the output into an output file

查看:317
本文介绍了从输入文件逐行输入,并使用strtok()和输出到输出文件中进行tokenize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是输入一个文件LINE BY LINE和tokenize并输出到一个输出文件。我已经能够做的是输入文件的第一行,但我的问题是,我不能输入下一行tokenize,以便它可以保存为输出文件中的第二行,这是我可以做的输入文件中的第一行。

What I am trying to do is to input a file LINE BY LINE and tokenize and output into an output file.What I have been able to do is input the first line in the file but my problem is that i am unable to input the next line to tokenize so that it could be saved as a second line in the output file,this is what i could do so far fro inputing the first line in the file.

#include <iostream>
#include<string>    //string library
#include<fstream>    //I/O stream input and output library

using namespace std;
const int MAX=300;    //intialization a constant called MAX for line length 
int main()
{
   ifstream in;     //delcraing instream
   ofstream out;    //declaring outstream

   char oneline[MAX];   //declaring character called oneline with a length MAX

   in.open("infile.txt");  //open instream
   out.open("outfile.txt");  //opens outstream
   while(in)
   {

    in.getline(oneline,MAX); //get first line in instream

    char *ptr;      //Declaring a character pointer
    ptr = strtok(oneline," ,");
    //pointer scans first token in line and removes any delimiters


  while(ptr!=NULL)
   {

    out<<ptr<<" ";    //outputs file into copy file
    ptr=strtok(NULL," ,");
    //pointer moves to second token after first scan is over 
   }

   }
   in.close();      //closes in file
   out.close();      //closes out file


   return 0;
}


推荐答案

C++ String Toolkit Library(StrTk)对您的问题有以下解决方案:

The C++ String Toolkit Library (StrTk) has the following solution to your problem:

#include <iostream>
#include <string>
#include <deque>
#include "strtk.hpp"

int main()
{
   std::deque<std::string> word_list;
   strtk::for_each_line("data.txt",
                        [&word_list](const std::string& line)
                        {
                           const std::string delimiters = "\t\r\n ,,.;:'\""
                                                          "!@#$%^&*_-=+`~/\\"
                                                          "()[]{}<>";
                           strtk::parse(line,delimiters,word_list);
                        });

   std::cout << strtk::join(" ",word_list) << std::endl;

   return 0;
}

更多示例请参见此处

这篇关于从输入文件逐行输入,并使用strtok()和输出到输出文件中进行tokenize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆