【问题标题】:Why am i getting the error "segmentation fault" when i run the program?为什么我在运行程序时收到错误“分段错误”?
【发布时间】:2013-11-05 23:47:25
【问题描述】:

我试图读入一个文件(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;
}

【问题讨论】:

  • 段错误和堆栈跟踪应该可以准确地告诉您问题出在哪里。
  • 找个不错的c++读取文件教程是个好主意,你有一些错误
  • 我目前正在尝试学习 c++,这是其中一个项目,但我被卡住了

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


【解决方案1】:

您正在使用循环变量为name 向量编制索引,以迭代word 字符串。由于您在那里有 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;
    }
}

【讨论】:

  • 我想要它,这样如果它实际上不是一个词,那么它就不会将它推入名称中。我应该添加一个 else 语句来说明它何时不是单词吗?
  • 然后把!isalpha改成isalpha
  • @Trenton:如果你使用std::vector::at(int),将会抛出异常而不是崩溃。
  • 谢谢,这肯定有帮助,它现在无限循环,但这是我的 for 循环的问题,我可以解决这个问题
  • 我认为更重要的一点是 OP 将 字符串容器中的名称数每个字符串中的字符数 混淆了.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 2017-10-20
相关资源
最近更新 更多