Variable Names using input File

So I have an imput file. I'm reading information from it line by line. Each line consists of a number and a string value. Later I have to read another text file and change the strings, that contain those numbers to the ones provided in the first file.
I wanted to do this, but I don't know if it's even possible:
for each line i read in the first file I create a new variable, that contains those numbers that are given in the line. For example i have line
"122 CEO"
and i want to create a variable
String str122 = "CEO";
Is this possible, if yes, then how?
I would use a std::map<std::string, std::string> with the key being the name and the value being, well, the value. ;)
http://www.cplusplus.com/reference/stl/map/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std; 


int _tmain(int argc, _TCHAR* argv[])
{
	string str1 = "This is the string no 239 will have to find out";
	string str = "STR";
	int len = str1.length();
	for( int i = 0 ; i < len; i++ )
	{
		if( isdigit(str1[i]))
			str +=str1[i];

	}
	cout<<"\n str = "<<str;
	return 0;
}
I tried to use map, I have something like this:
map<string, string> array;
and then i get information inside the map like this:
while (!input_file.eof())
{
getline(input_file, buf);
number_str = buf.substr(0, 3);
number_str = "#" + number_str;
cout << number_str;
str = buf.substr(4, buf.length());
array[number_str] = str;
}

Question is - how do i get the values later out of this map? Or am I doing something completely wrong here?

----------------------------------------------------------------------------------------------------------------------------------------------

To answer my own question:
to access the values you have to use something like this:
str = array[#002];

Or in my situation I use:
while ((off=txt.find("#", off))!=string::npos)
{
str = txt.substr(off, 4);
txt.replace(off, 4, array[str]);
}

Is this correct or should I change something?
Last edited on
You should use a map<string, string>::iterator and start it at array.begin(), then keep incrementing it with ++ until it equalsarray.end(). You can use YourIterator->first to get the key and YourIterator->second to get the value. You should only use this if you want to find out what all is in your map and don't already know.
Rather than this...
1
2
3
4
5
while (!input_file.eof())
{
    getline(input_file, buf);
    // ...
}

...you should have this:
1
2
3
4
while (getline(input_file, buf))
{
    // ...
}

The reason is that you should only use the input after you checked to see if the getline() function succeeded.

Topic archived. No new replies allowed.