File I/O manipulation

1
2
3
4
5
6
7
8
for (int y=0;y<MapH;y++)
    {
        for (int x=0;x<MapW;x++)
        {
fscanf(FileName, "%d:%d ", &a, &b);
}

}


This works really well for loading map using the format "A:A " but I want to use the C++ way, since we all know how fscanf, scanf, fprintf etc can screw you over.

can anyone help me with this, I want to be able to read in this format but I don't want to get each line to do so...

example:

1
2
3
4
5
6
0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 
0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 
0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 
0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 
0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 
0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 0:1 


I want to read it and then store 0:1 then move to the next one which is what fscanf does, so how would I go about doing this? ifstream ? if so, how?
Something like this perhaps:
1
2
3
4
5
6
std::ifsream ifs("myfilename.txt");

int a, b;
char c; // for readin the ':'

ifs >> a >> c >> b;
Last edited on
doesn't that just store the whole "text" in the file to those variable?

this doesn't work, I don't know if because of white space or new line?
The >> operator only reads in from the file information that matches the requested type. So if you ask for an int it will only read in an integer. Also it will skip any leading whitespace.

This code should work fine on your data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>

int main()
{
	std::ifstream ifs("input.txt");

	const size_t MapH = 6;
	const size_t MapW = 9;

	for(size_t y = 0; y < MapH; y++)
	{
		for(size_t x = 0; x < MapW; x++)
		{
			int a, b;
			char c; // for reading the ':'

			ifs >> a >> c >> b;

			std::cout << "a: " << a << '\n';
			std::cout << "b: " << b << '\n';
		}
		std::cout << '\n';
	}

	return 0;
}
Last edited on
I don't understand why it is working now and it wasn't a minute ago... but thanks a lot man, it is working now, but it is seriously weird, I had the same function with a char and everything but it just wasn't doing it :/

I deleted the whole function and rewrote it back, some time you could miss a single minuscule variable and it will mes you up... thanks again bro.
Topic archived. No new replies allowed.