Decoding character positions into a message

Hi!

I am trying to decode a text file that holds a pair of integers that represent [lineIndex, characterIndex(in that line)] and find the character with those positions in ANOTHER text file.

For example:

File1:
mary had
a little
lamb

File2
2 2
0 3
1 1
2 3
2 1
0 7


After decoding, I should have the output of "my bad". I've done this by hand and this is what I did:
2 2 is 'm' found in File1 lineIndex 2 characterIndex 2
0 3 is 'y' found in File1 lineIndex 0 characterIndex 3
1 1 is ' ' found in File1 lineIndex 1 characterIndex 1
2 3 is 'b' found in File1 lineIndex 2 characterIndex 3
2 1 is 'a' found in File1 lineIndex 2 characterIndex 1
0 7 is 'd' found in File1 lineIndex 0 characterIndex 7

Please help, I am so lost.

Thank you!
Create a vector of strings. Read file1 into that vector. Push each line read onto the vector.
Read file2 into a pair of numbers at a time.
Index into your vector of strings using the pair of numbers read.
Output the character at that position.

If you don't know how to do any of that, you need to go back and study: vectors, strings and file I/O.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main()
{
	ifstream			file1("file1.txt");
	ifstream			file2("file2.txt");
	vector<string>		lines;
	char 				temp[100];
	int				ln, cn;

	//	Read the file1 into the vector
	while (file1.getline(temp,100)) 
		lines.push_back(temp);
       //  Read file2 and index into the vector
	while (file2 >> ln >> cn)
		cout << lines[ln][cn];
	cout << endl;
}
Last edited on
without the files, same idea, maybe a little easier to see what is going on?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
	
string s[3] = 
{"mary had",
"a little",
"lamb"};

vector<int> c
{
2, 2,
0, 3,
1, 1,
2, 3,
2, 1,
0, 7
};

for(int i = 0; i < c.size(); i+=2)
 cout << s[c[i]][c[i+1]] ; 	//string [first index] [letter index]
}
  
Without file2 data checking:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>

int main() {
	if (std::ifstream cif { "file1.txt" }) {
		std::vector<std::string> cipher;

		for (std::string line; std::getline(cif, line); cipher.push_back(std::move(line)));

		if (std::ifstream ifs { "file2.txt" })
			for (unsigned lno {}, pos {}; ifs >> lno >> pos; )
				std::cout << cipher[lno][pos];
		else
			std::cout << "Cannot open data file\n";
	} else
		std::cout << "Cannot open cipher file\n";
}



my bad

Topic archived. No new replies allowed.