Reading a number from a C ++ file

I have a file with a simple number, for example:

66

or

126

How can I read this value intin C ++?

Please note that the file may also contain spaces or enter after the number.

I started like this:

int ReadNumber() 
{
    fstream filestr;
    filestr.open("number.txt", fstream::in | fstream::app);

    filestr.close()
}

How to proceed?

Thank.

+3
source share
3 answers

I really don't know why people use fstream with flags set when it only wants to do input.

#include <fstream>
using namespace std;

int main() {
    ifstream fin("number.txt");
    int num;
    fin >> num;
    return 0;
}
+5
source
int ReadNumber() 
{
    fstream filestr;
    int number;
    filestr.open("number.txt", fstream::in | fstream::app);
    filestr >> number;
    return number;
} // filestr is closed automatically when it goes out of scope.
+4
source

: - freopen.

#include <iostream>
using namespace std;

int readNumber(){
    int x;
    cin>>x;
    return x;
}

int main(){
    freopen ("number.txt","r",stdin);
    cout<<readNumber();
}
+2

Source: https://habr.com/ru/post/1751934/


All Articles