c++ how to build a 2D matrix of strings from a .dat file? 5 columns x rows

后端 未结 1 615
滥情空心
滥情空心 2021-01-19 04:31

I need to read a .dat file which looks like this:

Atask1 Atask2 Atask3 Atask4 Atask5
Btask1 Btask2 Btask3 Btask4 Btask5
Ctask1 Ctask2 Ctask3 Ctask4 Ctask5
Dt         


        
1条回答
  •  时光取名叫无心
    2021-01-19 04:57

    Your problem addresses a number of issues, all of which I will attempt to answer in one go. So, forgive the length of this post.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char argv[]){
      std::vector  v;//just a temporary string vector to store each line
    
      std::ifstream ifile;
      ifile.open("C://sample.txt");//this is the location of your text file (windows)
    
      //check to see that the file was opened correctly
      if(ifile.is_open()) { 
        //while the end of file character has not been read, do the following:
        while(!ifile.eof()) {
          std::string temp;//just a temporary string
          getline(ifile, temp);//this gets all the text up to the newline character
          v.push_back(temp);//add the line to the temporary string vector
        }
        ifile.close();//close the file
      }
    
      //this is the vector that will contain all the tokens that
      //can be accessed via tokens[line-number][[position-number]
      std::vector < std::vector > tokens(v.size());//initialize it to be the size of the temporary string vector
    
      //iterate over the tokens vector and fill it with data
      for (int i=0; i

    Note, I did not use iterators, which would have been beneficial here. But, that's something I think you can attempt for yourself.

    0 讨论(0)
提交回复
热议问题