2010-12-01 120 views
13

我想要做的是输入一个文件LINE BY LINE并标记并输出到输出文件中。我有什么能够做到的是输入文件中的第一行,但我的问题是,我无法输入下一行标记,以便它可以保存为输出文件中的第二行,这是我可以做到目前为止在文件中输入第一行。从输入文件逐行输入,使用strtok()和输出到输出文件的标记大小

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

回答

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 

输入:

一个,B C

去FG,hijklmn

输出:

A B C DE FG hijklmn

如果你想换行,在适当的点加out << endl;

14

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 ,,.;:'\"" 
                  "[email protected]#$%^&*_-=+`~/\\" 
                  "()[]{}<>"; 
          strtk::parse(line,delimiters,word_list); 
         }); 

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

    return 0; 
} 

更多的例子可以发现Here