简体   繁体   中英

Ifstream in c++

I need some help with a code.

I need to take this information to my c++ code from another file, the last one is just like this:

Human:3137161264 46

This is what I wrote for it, it takes the word "Human" correctly but then it takes random numbers, not the ones written on the file I just wrote:

struct TSpecie {
string id;
int sizeGen;
int numCs; };

__

TSpecie readFile(string file){
TSpecie a;
ifstream in(file);
if (in){
    getline(in,a.id,':');
    in >> a.sizeGen;
    in >> a.numCs;
}
else
    cout << "File not found";
return a; }

Hope you can solve it and thanks for your help

3137161264 causes integer overflow leading to Undefined Behaviour .

So unsigned int sizeGen would be enough for this case, but consider long long (unsigned) int sizeGen too.

Edit 1: As pointed out by @nwp in comments to your question, you can also check your stream if any error has occured:

//read something and then 

if (!in) { 
    // error occured during last reading 
}

Always test whether input was successful after reading from the stream:

if (std::getline(in, a.id, ':') >> a.sizeGen >> a.NumCs) {
   // ...
}

Most likely the input just failed. For example, the first number probably can't be read successful. Also note that std::getline() is an unformatted input function , ie, it won't skip leading whitespace. For example the newline after the last number read is still in the stream (at least, since your use of std::getline() finishes on a colon, it will only create an odd ID).

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