为什么我在运行程序时收到错误"segmentation fault"?

Why am i getting the error "segmentation fault" when i run the program?

本文关键字:错误 segmentation fault 运行 程序 为什么      更新时间:2023-10-16

我正在尝试读取文件(input.txt)并逐个字符串,并且仅将单词存储在向量(名称)中。 这是一个更大项目的一部分,但我被困在这里。该程序可以编译,但是当我运行它时,出现错误"分段错误"。我已经查看了我的程序,但找不到错误。我相信它在我的 for 循环中以及我的措辞方式,但不知道如何更改它以使程序正常运行。如果你能给我一些关于如何改变它的建议,甚至告诉我出了什么问题,这样我知道从哪里开始,那就太好了!谢谢!

#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<sstream>
using namespace std;

int main()
{
    ifstream inf;
    inf.open("input.txt");//open file for reading
    string s;
    getline(inf, s);
    string word;
    vector<int> index;// for later in my project ignore
    vector<string> name;// store the words from the input file
    while( !inf.eof())//while in the file
    {
            istringstream instr(s);//go line by line and read through the string
            string word;
            instr >> word;
            for(int i=0;i<word.length(); i++) //go word by word in string checkin if word and if it is then parseing it to the vector name
               {
                    if(!isalpha(word[i]))
                           name.push_back(word);
                cout<<name[i]<<endl;
            }
    }
    inf.close();
    return 0;
}

您正在使用用于迭代word字符串的循环变量为name向量编制索引。由于您在那里有一个if语句,因此完全有可能永远不会调用name.push_back(word);,并且您立即错误地索引到name

for(int i=0;i<word.length(); i++)
{
    // If this fails, nothing is pushed into name
    if(!isalpha(word[i]))
        name.push_back(word);
    // But you're still indexing into name with i.
    cout<<name[i]<<endl;
}

只需打印循环中的单词,无需索引向量。

for(int i=0;i<word.length(); i++)
{
    if(!isalpha(word[i]))
    {
        name.push_back(word);
        cout << "Found word: " << word << endl;
    }
}
相关文章: