How to read from a text file and split it into values in C++

this is my text file (mytext.txt):

rho_0,10
kp_0,8
Beta_kp,6
x_min,5
x_max,8
y_min,9
y_max,5
z_min,4
z_max,7
I want to read from this text file line by line and store each Value in the parameter at the same line. for example, for the first line store 10 in rho_0. I have written as below but I don't think it will save the value for the corresponding parameter. I know that I should split each line by delimiter and then convert string to double (float), but I don't know how to implement it for the lines.
Can someone help me?

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

using namespace std;

int main ()
{
string line;
ifstream myfile ("mytext.txt");

if (myfile.is_open())
while ( getline( myfile, line ))
    {
    cout <<line<<endl  ;
}

}


getline can be delimited by each comma by adding ',' as a third parameter.
istream >> operator can then we used to extract the number after the comma.
Also, the "myfile >> std::ws" part just consumes any whitespace before calling newline.

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

using namespace std;

int main ()
{
    ifstream myfile ("mytext.txt");

    if (!myfile.is_open())
    {
        std::cout << "Could not open file!\n";
        return 1;
    }

    std::string parameter;
    while (getline(myfile >> std::ws, parameter, ','))
    {
        double value;
        if (myfile >> value)
        {
            cout << parameter << " : " << value << '\n';
        }
    }
}
Try this:

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

int main()
{
	std::map <std::string, int> names;
	std::ifstream ifs("mytext.txt");

	if (!ifs.is_open())
		return (std::cout << "Cannot open file\n"), 1;

	for (std::string name; std::getline(ifs, name, ','); ifs.get()) {
		int num;

		ifs >> num;
		names[name] = num;
	}

	for (const auto& [name, value] : names)
		std::cout << name << "   " << value << '\n';
}


Giving:


Beta_kp   6
kp_0   8
rho_0   10
x_max   8
x_min   5
y_max   5
y_min   9
z_max   7
z_min   4

Thanks alot for your nice explanation, but I think still your program does not store value in the Parameters.
for examle If I want to cout 'xmin', according to your programm
It will give the error:
'x_min' was not declared in this scope.
Because at the next step I want to use x_min and x_max ... to calculate Volume. I mean
double Volume=(x_max-x_min)*(y_max-y_min)*(z_max-z_min) ; something like this is wrong?

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 <string>

using namespace std;

int main ()
{

   ifstream myfile ("mytext2.txt");

    if (!myfile.is_open())
    {
        std::cout << "Could not open file!\n";
        return 1;
    }

    std::string parameter;
    while (getline(myfile >> std::ws, parameter, ','))
    {
        double value;
        
        if (myfile >> value)
        {
           double Volume=(x_max-x_min)*(y_max-y_min)*(z_max-z_min) ;
           cout << Volume<<endl;
        }
    }
}
Variable names do not exist at run-time. You can't dynamically have a new variable name based off what's in the file.

Instead, if you use a std::map to store the values (mapping a string to number), like how seeplus did it, you can access or set a specific paramter's value through the std::map.

1
2
3
4
5
6
7
std::map <std::string, double> names;

// ... { add all the names & values from the file to the map through my or seeplus's method }

double& x_max = names["x_max"];
double& x_min = names["x_min"];
double Volume = x_max - x_min; // etc. 
Last edited on
Thank you so much.
Sorry that I Ask so many questions, just to be sure, It should be as below?
but I get at the end 9 zero !

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
35
36
37
38
39
#include <fstream>
#include <map>
#include <string>
#include <iostream>


using namespace std;

int main ()
{
    std::map <std::string, double> names;
    ifstream myfile ("mytext.txt");

    if (!myfile.is_open())
    {
        std::cout << "Could not open file!\n";
        return 1;
    }

    std::string parameter;
    while (getline(myfile >> std::ws, parameter, ','))
    {
        double value;
        if (myfile >> value)
        {
        double x_max = names["x_max"];
        double x_min = names["x_min"];
        double y_max = names["y_max"];
        double y_min = names["y_min"];
        double z_max = names["z_max"];
        double z_min = names["z_min"];
        double Volume = (x_max-x_min)*(y_max-y_min)*(z_max-z_min) ;

        cout << Volume<<endl;

        }

    }
}

That's what a forum is here for :)

You're very close. Don't calculate the volume inside the while loop.

Your code should be three parts, logically:
(1) open file
(2) parse file, fill data into the map
(3) calculate the volume given the data in the map

So inside your loop, just do:

1
2
3
double value;
myfile >> value;
names[parameter] = value; // adds a mapping from the parameter to its value 


Then, after the loop, use names["x_max"], etc, to calculate and print the volume.
Last edited on
Yes, thanks alot.
Now it's working :)
Topic archived. No new replies allowed.