为什么我在运行程序时收到错误"segmentation fault"?
Why am i getting the error "segmentation fault" when i run the program?
我正在尝试读取文件(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;
}
}
相关文章:
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 导致Segmentation错误的结构中的矢量
- OpenGL "Segmentation fault"错误
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 如何修复 C++ 中的'Segmentation fault'错误
- 尝试读取包含 ints 并存储在 int vector 中的文件,但我不断收到错误"Segmentation fault (core dumped)"
- 为什么当我更改此代码时会给我"segmentation fault"错误?
- 尝试将文本文件加载到动态分配的 2D 数组中时出现'Segmentation fault'错误
- 由于while循环中的条件,导致Segmentation错误
- 取消引用会导致Segmentation错误
- 调用构造函数定义中的函数后收到Segmentation Fault 11错误
- 为什么我在运行程序时收到错误"segmentation fault"?
- 当我尝试从结构列表中访问内存时出现错误:" Program received signal SIGSEGV, Segmentation fault."
- 当g++静态链接pthread时,导致Segmentation错误,原因何在
- 为什么我的程序在运行后给出"segmentation fault"(核心转储)错误
- 在Qt错误显示:"Fault Module Name: Qt5Cored.dll"在win 7和调试时:"segmentation fault"在CentOS Linux和Win 7中
- 引用字符串参数导致Segmentation错误
- 为什么 g++ 在将节点指向数据字符时返回'Segmentation fault'错误?
- "Segmentation fault"与"run time"错误?