There are several options for extracting values from a file and assigning them to variables in a C++ program. Here are three common methods:
John Doe
25
3.14
You can use the input stream operators to extract these values and assign them to variables in your program like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("data.txt");
string name;
int age;
double pi;
infile >> name >> age >> pi;
cout << "Name: " << name << endl; // output: Name: John Doe
cout << "Age: " << age << endl; // output: Age: 25
cout << "Pi: " << pi << endl; // output: Pi: 3.14
infile.close();
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("data.txt");
string line;
string name;
int age;
double pi;
getline(infile, line);
name = line;
getline(infile, line);
age = stoi(line);
getline(infile, line);
pi = stod(line);
cout << "Name: " << name << endl; // output: Name: John Doe
cout << "Age: " << age << endl; // output: Age: 25
cout << "Pi: " << pi << endl; // output: Pi: 3.14
infile.close();
return 0;
}
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <string>
using namespace std;
using namespace boost;
int main() {
ifstream infile("data.txt");
string line;
string name;
int age;
double pi;
getline(infile, line);
name = line;
getline(infile, line);
age = lexical_cast<int>(line);
getline(infile, line);
pi = lexical_cast<double>(line);
cout << "Name: " << name << endl; // output: Name: John Doe
cout << "Age: " << age << endl; // output: Age: 25
cout << "Pi: " << pi << endl; // output: Pi: 3.14
infile.close();
return 0;
}
Note: In all the above examples, we assume that the data in the file is in the correct format and matches the data type of the variable we are assigning it to. It is always a good practice to add error handling mechanisms to handle data that does not match the expected format.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-11-06 11:00:00 +0000
Seen: 10 times
Last updated: Dec 04 '21
What is the method to get a printable output of a C++11 time_point?
What is the process of redefining a c++ macro with fewer parameters?
How can a list be sorted alphabetically within a console application?
How can boost c++11 be used to resolve the symlinks of a file path?
What distinguishes the jsonlite and rjson packages from each other at their core?
How can the issue of accessing a member within an address that is misaligned be resolved at runtime?
Does a C++ constructor get passed down through inheritance?
What is the difference between deallocating memory in C and deallocating memory in C++?