简体   繁体   English

使用fstream从txt文件获取行

[英]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". 因此,这是我的代码,用于读取一行并将其存储在arrAtoms []中(如果它以“ ATOM”开头)。 For some reason, I keep getting the error Thread1: EXC_BAD_ACCESS(code=EXC_1386_GPFLT) and I have no clue why. 由于某种原因,我一直收到错误Thread1:EXC_BAD_ACCESS(code = EXC_1386_GPFLT),我不知道为什么。 Please help! 请帮忙!

The code runs quite fine on my machine. 代码在我的机器上运行得很好。 Maybe the problem is that the file has more ATOM entries than 700? 也许问题是该文件的ATOM条目超过700个? And your string array can only containg 700. If you don't know how many entries there will be, try using a vector 而且您的字符串数组只能包含700。如果您不知道会有多少个条目,请尝试使用向量

This is the file I tested the code on: 这是我测试代码的文件:

soadiaodiaodsa 沙丁鱼
sdaiod sadoiasoda sodaod sadoiasoda
ATOM alodaskd ATOM阿洛达斯克
ATOM alosad ATOM阿洛萨德
ATOM lol ATOM哈哈
saodai aosdisoad daiosiadsa 绍达奥斯蒂索阿德代萨德萨
ATOM ATOM ATOM 原子原子原子
ATOM LOL test ATOM LOL测试
lololololol 洛洛洛尔

I also tried outputting the first 15 entries in the array and it works fine and consists only of lines starting with ATOM: 我还尝试输出数组中的前15个条目,并且效果很好,并且仅包含以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. 您正在使用长度为700的array 。如果您的文件有700多个以“ ATOM”开头的行,则会发生内存分配错误。 A better way to do this is to use vector , so you don't need to worry about the size of the file. 更好的方法是使用vector ,因此您不必担心文件的大小。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM