繁体   English   中英

如何从文件中读取特定数据到数组字符串

[英]How to read specific data from file into array string

wer234 cwx1 20139   

asd223 cwx2 09678 

sda232 cwx3 45674 

ukh134 cwx4 23453 

plo209 cwx5 09573 

如何将数据读入三个字符串数组? 第一列进入第一字符串数组,第二列进入第二字符串数组,第三列进入第三字符串数组。 这是我尝试过的代码,但是最后一个数组进入了一行。

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


 }

如果您考虑的是大文件,则将整个文件放在一个字符串中可能效率很低。

您要实现的目标实际上并没有您预期的那么复杂(至少在c ++中如此)。 您可以这样做:

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

我以其他方式尝试过,让我们了解下面的简单代码。

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列时,此代码才有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM