Loading numbers from .txt-file into integer variable

Hi guys

How can I store 2 numbers in a .txt-file in two diffrent variables? The .txt-file Looks like this:

1024
520
00:0 00:0 00:0 00:0 00:0
00:0 00:0 00:0 00:0 00:0
00:0 00:0 00:0 00:0 00:0
00:0 00:0 00:0 00:0 00:0
00:0 00:0 00:0 00:0 00:0
and so on...

The two top numbers are MapWidth/MapHeight. I've used to pass them as arguments in functions, but it's inconvenient now. So how can I save those two numbers separately using fscanf()? How can I tell it to stop after the first number and store the second number in the second integer variable?

(Btw: The '00:0' is the map which is already loaded correctly by using the FILE* structure and fscanf while Looping through)

Thanks!
Last edited on
uhm, why do you want to use the c-function fscanf?
Why don't you use the c++ library instead?

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

int main()
{
    std::ifstream file("file.txt"); // your filename

    int width;
    int height;
    if(file.is_open()) 
    {
	file >> width;
	file >> height;

	std::cout << "width: " << width << std::endl;
	std::cout << "height: " << height << std::endl;
    }

    return 0;
}
Last edited on
Oh well ^^ I got it to work with fscanf()

I don't use the c++ style cauz I don't know how >.< How can I load the map which has the Format TileID:TypeID with your way? Loading simple words is easy, but I can't apply that on some more diffculte formats...
How can I load the map which has the Format TileID:TypeID

read an integer TileID, if that exists ignore the next character and read TypeID
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
29
30
31
32
33
34
#include <fstream>
#include <iostream>

int main()
{
    std::ifstream file("file.txt"); // your filename

    int width;
    int height;
    if(file.is_open()) 
    {
        file >> width;
        file >> height;
        std::cout << "width: " << width << "\nheight: " << height << std::endl;

        int tile;
        int type;

        // for all tiles
        while(file >> tile) // if there is one more tile
        {
            // ignore the next character 
            file.ignore(1);

            // get type
            file >> type;

            // do something with tile and type
            std::cout << "tile: " << tile << "\ntype: " << type << std::endl;
        } 
    }

    return 0;
}
Last edited on
Topic archived. No new replies allowed.