从输入文件逐行输入并使用strtok()标记并输出到输出文件中

时间:2010-12-01 20:19:13

标签: c++ string visual-c++ iostream tokenize

我要做的是输入一个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;
}

2 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:1)

当C ++使这个更整洁时,你正在使用C运行库。

在C ++中执行此操作的代码:

ifstream in;     //delcraing instream
ofstream out;    //declaring outstream

string oneline;

in.open("infile.txt");  //open instream
out.open("outfile.txt");  //opens outstream
while(getline(in, oneline))
{
    size_t begin(0); 
    size_t end;
    do
    {
        end = oneline.find_first_of(" ,", begin);

        //outputs file into copy file
        out << oneline.substr(begin, 
                    (end == string::npos ? oneline.size() : end) - begin) << ' ';

        begin = end+1;
        //pointer moves to second token after first scan is over 
    }
    while (end != string::npos);
}

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

输入:

  

a,b c

     

de fg,hijklmn

输出:

  

a b c de fg hijklmn

如果您想要换行,请在适当的位置添加out << endl;