将两列的文件读入一个数组

Reading a file of two columns into one array

本文关键字:一个 数组 两列 文件      更新时间:2023-10-16

我有一个非常基本的问题。我正在尝试从保存如下数据的文件中读取:

Collins, Bill
Smith, Bart
Allen, Jim
.
.
.
Holland, Beth

我希望我的代码读取数据并将它们保存到数组的一列中。所以我所做的是,

#include<iostream>
#include<string>
#include<cstring>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
string first, last, FIRST[200], LAST[200];
ifstream infile;
infile.open("names.dat");
while (!infile.eof())
{
for (int i = 0; i < !infile.eof(); i++)
{
    infile >> first;
    FIRST[i] = first;
    cout << FIRST[i] << " ";
    infile >> last;
    LAST[i] = last;
    cout << LAST[i] << " " << endl;
    }
}
return 0;
}

但是,我只需要一个名为 NAME[] 的数组,而不是两个(FIRST[] 和 LAST[])。所以基本上如果我叫NAME[0],那就是柯林斯,比尔。

我真的不知道该怎么做...阅读资料让我更加困惑。

这只是我必须编写的整个程序的一小部分,该程序按字母顺序对名称进行排序,我什至还没有通过这个阶段。

您可能只阅读每一行:

#include<iostream>
#include<fstream>
#include<deque>
int main()
{
    std::deque<std::string> names;
    std::ifstream infile("names.dat");
    std::string name;
    while(getline(infile, name))
        names.push_back(name);
    return 0;
}

EOF测试通常不是成功输入的测试。在这里,getline返回流,条件while(stream)是测试流状态。

关于评论:

#include<algorithm>std::sort(names.begin(), names.end());

只需使用一个字符串数组而不是两个。

int main()
{
   string first, last, NAME[200];
   ifstream infile;
   infile.open("names.dat");
   int i = 0;
   while (true)
   {
      infile >> first;
      infile >> last;
      if (!infile.eof() && infile.good() )
      {
         NAME[i] = last + ", " + first;
         cout << NAME[i] << std::endl;
      }
      else
      {
         break;
      }
      ++i;
   }
   return 0;
}

只需使用二维数组,如下所示:

主.cpp

#include<iostream>
#include<string>
#include<cstring>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
    string first, last, myarray[200][2];
    ifstream infile;
    infile.open("names.dat");
    int i = 0;
    while (!infile.eof()) {
        infile >> first;
        myarray[i][0] = first;
        cout << myarray[i][0] << " ";
        if (infile.eof()) {
            cout << endl;
            break;
        }
        infile >> last;
        myarray[i][1] = last;
        cout << myarray[i][1] << " " << endl;
        ++i;
    }
    return 0;
}

输出

Collins, Bill
Smith, Bart
Allen, Jim

话虽如此,我个人通常会在C++中使用std::array或一些更智能的容器类型。

相关文章: