我有一个非常基本的问题。我正在尝试从保存数据的文件中读取:
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 []&amp; LAST [])。所以基本上如果我打电话给NAME [0]将是柯林斯,比尔。
我真的不知道该怎么做...阅读资料让我更加困惑......
这只是我必须编写的整个程序的一小部分,它按字母顺序排序名称,我还没有通过这个阶段。
答案 0 :(得分:2)
您可能只是阅读每一行:
#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());
答案 1 :(得分:1)
然后按如下方式使用2D维数组:
#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或更智能的容器类型。
答案 2 :(得分:1)
只使用一个字符串数组而不是两个字符串。
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;
}