将文本文件中的字符串保存到数组c ++中

时间:2013-05-01 16:44:58

标签: c++ arrays for-loop text-files

我的文字文件就像

Alex Garcia 1000 userid password
Sana Lopez 300 uid pwd

我想在2D数组中保存上面的文本文件

ifstream Records("customerdata.txt");
string dataarray[6][6];

    if (Records.is_open())
     {
         while ( Records.good() )
            {
                for(int i=0; i<6; i++)
                {
                    for(int j=0; j<6; j++)
                    {
                        getline(Records,dataarray[i][j],' ');

                    }


                }
            }
        Records.close();
    }
     else cout << "Unable to open file"; 

当我尝试使用for循环输出数组时,我得到了一些值。我不知道我做错了什么。

1 个答案:

答案 0 :(得分:0)

你需要使用类似的东西来标记你读取的每一行,加上你的数据阵列大于读入的记录数,你只有两行而不是6行。

ifstream Records("customerdata.txt");
string dataarray[6][6];

  if (Records.is_open())
   {
          while ( Records.good() )
          {
             size_t row=0;
             size_t col=0;
             std::string myLine;
             getline(Records,myLine);
             std::istringstream nlineSteam(myLine);
             std::string token;
             while(nlineSteam >> token){
              dataarray[row][col]=token;
              col++;
             }
             row++;
             col=0;

          }
    Records.close();
}
 else cout << "Unable to open file";
相关问题