Reputation: 1
This is how the program looks and i need to make all integers with different name. Like x,x1,x2 and so on...
#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;
}
Upvotes: 0
Views: 1675
Reputation: 57688
If you are associating numbers with names, a std::map
(an associative container), is the data structure to use:
#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";
Upvotes: 0
Reputation: 490108
This sort of situation is why arrays were invented. The syntax changes slightly, so you use x[1]
, x[2]
, and so on, instead of x1
, x2
, and so on, but other than that it's pretty much exactly what you seem to want.
Upvotes: 1
Reputation: 9866
Do the names all need to be distinct, or is it acceptable to put the numbers into a collection? If so, you can do something like this to read in the numbers.
vector<int> numbers;
ifstream fin("infile.txt");
int x;
while( fin >> x ) {
numbers.push_back(x);
}
Upvotes: 4