0

Can someone teach me what's the error in my code? The exception is thrown at line ifs >> Acc[i].num_followers;. Am I facing any pointer issues?

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

struct Followers {
    string title = "", tag = "";
    int num_followers = 0;
};

void readInput(Followers Acc[], int& totalAccount) {
    ifstream ifs("Followers.txt");
    for (int i = 0; !ifs.eof(); i++) {
        getline(ifs, Acc[i].title);
        getline(ifs, Acc[i].tag);
        ifs >> Acc[i].num_followers;
        totalAccount += 1;
    }
}

int main() {
    Followers acc[5];
    int total = 0;
    readInput(acc, total);
    cout << total;
    return 0;
};

This is the text file.

Instagram
@instagram
290000000
Cristiano Ronaldo
@cristiano
160000000
The Rock
@therock
137000000
Ariana Grande
@arianagrande
150000000
Selena Gomez
@selenagomez
148000000
  • `!ifs.eof()` could cause bad behavior. Also your code has no checking for keeping inside the bounds of the array. – drescherjm May 05 '22 at 01:41
  • May i know the details? – user18343496 May 05 '22 at 01:42
  • [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm May 05 '22 at 01:42
  • Your code would be better if you used `std::vector` instead of the fixed sized array. – drescherjm May 05 '22 at 01:44
  • 1
    This might be worth a read too: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Retired Ninja May 05 '22 at 01:45
  • Did you try using a debugger? A debugger will easily show all the problems in the shown code. Like how it's not reading what you think it does, because of mixing `>>` together with `std::getline`. And after this is fixed the broken eof logic results in one extra iteration, and more demons flying of of everyone's nose because of complete lacks of bounds checking resulting in an array overrun. – Sam Varshavchik May 05 '22 at 02:11
  • Ya I just add one more ifs.ignore(); below the ifs >> Acc[i].num_followers; and then the bug is fixed. – user18343496 May 05 '22 at 04:04
  • Ok thanks I will go and check the bounds of the array. – user18343496 May 05 '22 at 04:05

0 Answers0