这是程序的外观,我需要使用不同的名称制作所有整数。像x,x1,x2等......
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (true) {
int x;
iFile >> x;
if( iFile.eof() ) break;
cerr << x << endl;
}
system("Pause");
return 0;
}
答案 0 :(得分:4)
这些名称是否都需要区分,或者将数字放入集合中是否可以接受?如果是这样,你可以做这样的事情来读数字。
vector<int> numbers;
ifstream fin("infile.txt");
int x;
while( fin >> x ) {
numbers.push_back(x);
}
答案 1 :(得分:1)
这种情况是阵列发明的原因。语法略有变化,因此您使用x[1]
,x[2]
等,而不是x1
,x2
等等,但除此之外,它几乎完全相同你似乎想要什么。
答案 2 :(得分:0)
如果要将数字与名称相关联,则std::map
(关联容器)是要使用的数据结构:
#include <map>
#include <string>
#include <iostream>
using std::map;
using std::string;
using std::cout;
typedef std::map<string, int> Data_Container;
//...
Data_Container my_container;
//...
my_container["Herman"] = 13;
my_container["Munster"] = 13;
cout << "Herman's number is: " << my_container["Herman"] << "\n";