简体   繁体   中英

Getting line from a txt file using fstream

int main(int argc, const char * argv[])
{
    ifstream input;
    input.open("test.txt");
    string arrAtoms[700];
    string temp;
    int i = 0;
    while(getline(input, temp)){
        if(startsWithAtom(temp)) {
            arrAtoms[i] = temp;
            i++;
        }
    }
    return 0;                
}

bool startsWithAtom(string test) {
    string atom = "ATOM";
    if(test.find(atom) == 0) {
        return true;
    }
    return false;
}

So this is my code to read a line and store it in arrAtoms[] if it starts with "ATOM". For some reason, I keep getting the error Thread1: EXC_BAD_ACCESS(code=EXC_1386_GPFLT) and I have no clue why. Please help!

The code runs quite fine on my machine. Maybe the problem is that the file has more ATOM entries than 700? And your string array can only containg 700. If you don't know how many entries there will be, try using a vector

This is the file I tested the code on:

soadiaodiaodsa
sdaiod sadoiasoda
ATOM alodaskd
ATOM alosad
ATOM lol
saodai aosdisoad daiosiadsa
ATOM ATOM ATOM
ATOM LOL test
lololololol

I also tried outputting the first 15 entries in the array and it works fine and consists only of lines starting with ATOM:

for(unsigned int i=0;i<15;i++)
  cout << arrAtoms[i] << endl;

You are using array with length 700. If your file have more than 700 lines that start with "ATOM", a memory allocation error will happen. A better way to do this is to use vector , so you don't need to worry about the size of the file.

#include <vector>
int main(int argc, const char * argv[])
{
    ifstream input;
    input.open("test.txt");
    std::vector <string> arrAtoms;
    string temp;
    while(getline(input, temp)){
    if(startsWithAtom(temp)) {
        arrAtoms.push_back(temp);
      }
    }
    return 0;                
}

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