c++ 从输入文件逐行输入,并使用strtok()和输出到输出文件

我想要做的是输入一条文件LINE BY LINE,并将其输入到输出文件中.我能够做的是输入文件中的第一行,但是我的问题是我无法输入下一个行进行标记化,以便它可以保存为输出文件中的第二行,这是我可以做的,迄今为止,输入文件中的第一行.

#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)对您的问题有以下解决方案:

#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;
}

更多的例子可以发现Here

转载注明原文:c++ 从输入文件逐行输入,并使用strtok()和输出到输出文件 - 代码日志