【问题标题】:Save strings from text file into array c++将文本文件中的字符串保存到数组c++中
【发布时间】:2013-05-01 16:44:58
【问题描述】:

我的文本文件是这样的

Alex Garcia 1000 userid password
Sana Lopez 300 uid pwd

我正在尝试将上述文本文件保存在二维数组中

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 循环输出数组时,我会丢失一些值。我不知道我做错了什么。

【问题讨论】:

  • 我强烈建议在 StackOverflow 中搜索“[C++] 文本文件数组”。最近这类问题太多了。
  • 同时搜索“[c++] parse input file”。
  • c++ read text file into array 的可能重复项

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


【解决方案1】:

您需要使用类似这样的方法标记您读入的每一行,再加上您的数据阵列大于读入的记录数,您只有两行而不是 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";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多