Reading file using getline

Hi, I have an issue with reading from file using getline.

I know what the issue is just not how to solve it.
So I have a file with some data in it.

For example something like this:

Texture=../Textures/player.png
Name=Anders
Size=64

what I want to do is read the "key"-value up til' the '=' and do a comparison.
If I use getline(ifstream, someString, '=') the first iteration will be fine, someString will have "Texture" but the next iteration is not fine because it will read from after the '=' to the next one. So next iteration would be ../Textures/player.png\nName

I appriciate any help I can get.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
    std::ifstream stream("test.txt");
    std::string s;
    std::string t("Name");

    while(std::getline(stream, s, '=')){
        if(t == s){
            //t is the same as s
            //do something
        }
          
    }
    return 0;
}
This may not be exactly what you are looking for, but it may be a hint at least:
I've uses a stringstream for testing, as a substitute for a file. The code should be compatible if stream was a std::ifstream.

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
#include <iostream>
#include <sstream>

std::istringstream stream(

"Texture=../Textures/player.png\n"
"Name=Anders\n"
"Size=64\n"

);

bool read(std::istream & is, std::string & key, std::string & value)
{  
    getline(is, key, '=');
    getline(is, value);
    return bool(is);
}


int main()
{
    std::string key;
    std::string value;
    
    while (read(stream, key, value))
    {
        std::cout << "key = " << key
                  << "    value = " << value
                  << '\n';                  
    }
}

Where it may need some attention is if the second value is expected to be numeric. You could convert afterwards:
1
2
3
4
5
        if (key == "Size")
        {
            int n = std::stoi(value);
            std::cout << "n = " << n << '\n';
        } 

Hello Anders Ekdahl,

Similar to Chervil's approach, but keeping with your code:

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
#include <iostream>
#include <fstream>
#include <sstream>


int main()
{
	std::ifstream stream("test.txt");
	std::string s;
	std::string t("Name");

	while (std::getline(stream, s))
	{
		std::string key{ "" }, value{ "" };

		std::istringstream ss(s);
		std::getline(ss, key, '=');  // <--- Reads up to '='
		std::getline(ss, value);  // <--- Reads rest of line.

		if (t == key)  // <--- set a break point here to check key and value variables.
		{
			//t is the same as s
			//do something
		}

	}

	return 0;
}


Hope that helps,

Andy
Wow! Thanks guys :)

that was way better than I expected, truly grateful!
Topic archived. No new replies allowed.