开发者

Reading a number from file C++

开发者_Python百科

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.


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;
}


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.


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜