Associate file content to variable

closed account (21vXjE8b)
There's a way to associate some .txt content with specific variables?
Something like this:

[in .txt file]
123
456
789

[in code]
int a = 123, b = 456, c = 789;

With ifstream functions I could only print each line of the file. Maybe I've missed some information...
***Sorry if I didn't post a code, it's because I got rid of it... But if it's necessary, I'll try to redo it =D
Last edited on
If you read a file, you first put the information in a variable and later you might print the values of those variables, but you could also do something else with them. You could for example try to convert a string to an integer (http://www.cplusplus.com/reference/string/stoi/) or to a float (http://www.cplusplus.com/reference/string/stof/).

But you have to be careful, exceptions will be thrown if you try to parse a string that does not contain a number.
1
2
3
int integerValue = std::stoi("42");            // this will work
float floatValue = std::stof("42.0");          // this will work
int crashValue = std::stoi("hello world");  // this will crash your program if you don't catch exceptions 


Kind regards, Nico
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <fstream>

int main()
{
    iftstream file("file.txt"); // declare and open file
    
    int a, b, c; // declare 3 int variables

    file >> a >> b >> c; // put file contents into variables    
}


Like this?
Last edited on
closed account (21vXjE8b)
Thank you Arslan7041! It's the fastest way to do this.
Thank you too, Nico. Your way worked fine! A little bit longer, but I got the expected result ^^.
Topic archived. No new replies allowed.