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

标签 c++ arrays string file

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

关于c++ - 如何从文件中读取特定数据到数组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37284760/

相关文章:

c++ - 我如何在 C++ 上使用 Interop 创建 excel 文件

algorithm - 如何掌握就地数组修改算法?

c# - foreach 循环中一串单词的 ToUpper 方法不起作用

c - 如何指向数组

java - 如何在 Java 中漂亮地打印 3D 数组

java - 如何在 Java 中比较字符串?

c - 当数组不包含 null 终止符时,为什么 strlen() 返回奇怪的结果?

c++ - 如何在不使用 opencv 的情况下通过 C++ 中的原始图像形式来降低亮度?

c++ - 所以文件: function called from another so file than intended

c++ - 关联容器的 lower_bound 复杂度 : member function vs non-member function