2010-12-01 20 views
13

私がやろうとしているのは、ファイルをLINE BY LINEで入力し、出力ファイルに出力することです。できたのはファイルの最初の行ですが、私の問題は次の行をトークン化することができないため、出力ファイルに2行目として保存できるようになったことです。ファイル内の最初の行を入力します。入力ファイルから行ごとに入力し、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

出力:

B、Cデ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

関連する問題