How to use the output of a text file

Dear all,

I would like to use a fonction to read the value (int) within a text file.
The text file contains just one line with an Int value (0/1).
So, to read the text file, I use this:

1
2
3
4
5
6
7
8
      ifstream fichier(valGPIO);

    if(fichier)
    {
        string ligne;
        getline(fichier, ligne);
        cout << ligne << endl;
    }


And there is no problem. The output is correct, for example I got on console a value = 1 or 0.
My problem is how can I get this value (0/1)from the console to use it within a program ?

In fact, this value will be useful to activate another function.
For example, if the output is 0, do nothing, if 1 then do smart thing ;-)

Thank you for your help and support

Regards,

Replace lines 5-7 with:
1
2
3
int i;
fichier >> i;
cout << i << endl;

Last edited on
if it is always just a zero or one, you can use that to make the code simple.
if(ligne[0] == '0')
//do something
else
//do other action

if it is more complicated, you may need to turn the string into an integer to 'use' it depending on the purpose of the code.

you do not 'get it from the console' ... you use what you read from the file directly.

put all that together...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool should_i_do_it(string &valGPIO)
{
ifstream fichier(valGPIO);

    if(fichier)
    {
        string ligne;
        getline(fichier, ligne);
   //   cout << ligne << endl;
        fichier.close(); //cleaner
        return ligne[0] == '1'; //returns true if '1', false if not. 
    }
        return 0; //file failed to open, return false as best answer ? or do something else? exit(0)?
}

main
if(should_i_do_it(filename))
  function();



Last edited on
Thank you so much for your help.
Regards,
Topic archived. No new replies allowed.