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

标签 c++ for-loop segmentation-fault istringstream

我正在尝试读入一个文件 (input.txt) 并逐个字符串地读取并仅将单词存储在 vector (名称)中。这是一个更大项目的一部分,但我被困在这里。该程序编译但是当我去运行它时我得到错误“Segmentation Fault”。我查看了我的程序,但找不到错误。我相信它在我的 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 vector 建立索引。因为你在那里有一个 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;
}

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

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

关于c++ - 为什么我在运行程序时收到错误 "segmentation fault"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19801389/

相关文章:

Javascript 以循环方式遍历 12 部分数组

javascript - 如何使用 javascript 将图像数组显示为列表并使其可单击以显示一些文本?

c - 为 2D 数组分配内存时出现段错误(核心转储)

macos - 在 Mac OS X 10.6.3 上使用 HandVU 和 OpenCV

c++ - libtorrent 内置跟踪器

c - 在 c 中输入无效后重新提示用户

c++ - 在不同的线程上发送和接收

node.js seg 错误,stdout 没有报告任何错误

c++ - 从CMake中的lib目录加载共享库?

c++ - 类与枚举类作为索引类型