tags:

views:

96

answers:

3

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

66

or

126

How can I read it to a int value in C++?

Note that the file may also contain some spaces or enters after the number.

I started like so:

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

    filestr.close()
}

How to continue?

Thanks.

+4  A: 
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.
AraK
seems odd opening in append mode when you want to read...
Anders K.
@Andres K. I just copied his definition and add the code to it.
AraK
+2  A: 

Here's a neat trick: You can redirect standard i/o using freopen.

#include <iostream>
using namespace std;

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

int main(){
    freopen ("number.txt","r",stdin);
    cout<<readNumber();
}
Cam
+5  A: 

I don't really know why people are using fstream with set flags when he only wants to do input.

#include <fstream>
using namespace std;

int main() {
    ifstream fin("number.txt");
    int num;
    fin >> num;
    return 0;
}
Jamie Wong