2016-05-17 13 views
0
wer234 cwx1 20139 

asd223 cwx2 09678 

sda232 cwx3 45674 

ukh134 cwx4 23453 

plo209 cwx5 09573 

3文字列の配列にデータを読み取るにはどうすればよいですか? 最初の列を1番目の文字列配列に、2番目の列を2番目の文字列配列に、3番目の列を3番目の文字列配列に変換します。 これは私が試したコードですが、最後の配列が行に入ります。ファイルから特定のデータを配列文字列に読み取る方法

#include <iostream> 
#include <string> 
#include <sstream> 
#include <fstream> 

using namespace std; 
int main(){ 
    //load the text file and put it into a single string: 
    std::ifstream in("test.txt"); 
    std::stringstream buffer; 
    buffer << in.rdbuf(); 
    std::string test = buffer.str(); 
    std::cout << test << std::endl << std::endl; 

//create variables that will act as "cursors". we'll take everything between them. 
size_t pos1 = 0; 
size_t pos2; 

//create the array to store the strings. 
std::string str[5]; 
std::string str2[5]; 
std::string str3[5]; 

int x; 
int y; 

for(y=0; y<5;y++){ 



    for (x=0; x<3; x++){ 

     pos2 = test.find(" ", pos1); //search for the bar "|". pos2 will be where the bar was found. 

     if(x==0){ 

     str[y] = test.substr(pos1, (pos2-pos1)); //make a substring, wich is nothing more 

     }else if(x==1){ 

     str2[y] = test.substr(pos1, (pos2-pos1)); //make a substring, wich is nothing more 


     }else if(x==2){ 

     str3[y] = test.substr(pos1, (pos2-pos1)); //make a substring, wich is nothing more 


     }          //than a copy of a fragment of the big string. 
     // std::cout << str[x] << std::endl; 
     // std::cout << "pos1:" << pos1 << ", pos2:" << pos2 << std::endl; 
     pos1 = pos2+1; // sets pos1 to the next character after pos2. 
         //so, it can start searching the next bar |. 




    } 



} 

for (int p=0; p<5; p++){ 

    cout << str[p] <<endl; 
    cout << str2[p] <<endl; 
    cout << str3[p] <<endl; 

} 


    return 0; 


} 
+1

「演算子>>」を使用するだけです。 – LogicStuff

+2

ifstreamで直接 'operator >>'を使わないのはなぜでしょうか?>> str [y] >> str3 [y]; ' –

答えて

0

私は別の方法で試しましたが、下の簡単なコードを理解してみましょう。

while(in.good()) 
{ 
string stri; 
int i=1,a=0,b=0,c=0; 
in >> stri; 

switch(i%3) { 
case 1: 
str[a]=stri; 
a++; 
break; 
case 2: 
str2[b]=stri; 
b++; 
break; 
case 3: 
str3[c]=stri; 
c++; 
break; 
} 
i++; 

} 

ここで変数abcカウント配列インデックス。ループごとに、(i%3)が計算され、正しい配列が埋められます。

コードに問題がある可能性があります。私はそれをテストしなかった。

注記このコードは、3つの列がある場合にのみ機能します。

2

ファイル全体を1つの文字列にすることは、非常に大きなファイルを考えると非常に非効率的になります。

あなたが達成しようとしている目標は、(少なくともC++では)期待していたほど複雑ではありません。

for(size_t ind = 0; ind < 5; ++ind) 
    in >> str[ind] >> str2[ind] >> str3[ind]; 
+0

yes、> >演算子は単純に効率的ですが、データに名前のようにスペースがある場合はどうなりますか:Adam Maxwell全体の名前を1文字列に保存する必要があります。しかし、>>演算子はAdamを1文字列、Maxwellをもう1文字列と考えます。 –

+0

明確にするには:区切り文字は何ですか?スペースか "|"両方ともあなたのコードに存在するからですか? – threaz

関連する問題