简体   繁体   中英

Reading a file line by line and storing as an integer variable C++

I am a beginner in c++. I am trying to read a file and want to save it as an integer variable. In my file I have.

4
3
1

Now I want the variables to have the following values

fu_unit_adder=4                                                                         
fu_unit_mult=3
fu_unit_div=1

what should I do??

my code so far:

#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <cstdlib>
#include <stdio.h>

using namespace std;


int main()
{
    int  fu_unit_adder;
    int  fu_unit_mult;
    int  fu_unit_div;

    ifstream config_file ("config.txt");
    if (config_file.is_open())
    {
        for (int j = 0; j < 3; j++)
        {
            getline(config_file,fu_unit[j]);
            cout << fu_unit[j] << endl;
        }
    }
    system("pause");
    return 0;
}

If you know your file is going to be in that format, you might as well just use >> to extract from the file. You could do it as simply as this:

ifstream config_file ("config.txt");
config_file >> fu_unit_adder >> fu_unit_mult >> fu_unit_div;

If instead you want an array of units fu_unit that you might extend at some point, then you could do it like this:

ifstream config_file ("config.txt");
int fu_unit[3];
for (int i = 0; i < 3; i++) {
  config_file >> fu_unit[i];
}

If you want it a little more robust, you could check if the extractions are successful like so:

ifstream config_file ("config.txt");
int fu_unit[3];
for (int i = 0; i < 3; i++) {
  if (!(config_file >> fu_unit[i])) {
    // Extraction i failed, make sure you do config_file.clear() to continue
  }
}

If you know that the order of the data in the file is fixed and the count is 3 always, you may try:

getline(config_file,fu_unit_adder);
getline(config_file,fu_unit_mult);
getline(config_file,fu_unit_div);

There is no use to add a loop for only 3 variables. 3 statements would just be fine (if this is the case).

config_file.seekg(0,config_file.beg);
config_file >> fu_unit_adder;
config_file >> fu_unit_mult;
config_file >> fu_unit_div;

This should work for reading the first three variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM