[英]Why am i getting the error “segmentation fault” when i run the program?
I am attempting to read in a file (input.txt) and go string by string and storing only the words in a vector (name). 我试图读取文件(input.txt)并逐个字符串并仅将单词存储在向量(名称)中。 this is a part of a bigger project however I am stuck here. 这是一个较大项目的一部分,但是我被困在这里。 The program compiles however when i go to run it i get the error "Segmentation Fault". 但是,当我运行该程序时,会出现错误“ Segmentation Fault”。 i have looked through my program and cannot find the error. 我已经查看了我的程序,找不到错误。 i believe it to be in my for loop and how i have it worded but do not know how to change it to make the program run correctly. 我相信它会在我的for循环中以及我的措辞如何,但不知道如何更改它以使程序正确运行。 If you could give me some advice on how to change it or even tell me whats wrong so i know where to start that would be great! 如果您能给我一些有关如何更改它的建议,甚至告诉我出了什么问题,让我知道从哪里开始,那会很棒! thanks! 谢谢!
#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;
}
You're indexing the name
vector with the loop variables you're using to iterate the word
string. 您正在使用用于迭代word
字符串的循环变量来索引name
向量。 Since you have an if
statement there, it's entirely possible that name.push_back(word);
由于那里有一个if
语句,因此完全有可能name.push_back(word);
is never called, and immediately you're wrongly indexing into name
. 永远不会被调用,而您马上就会错误地索引到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;
}
Just print the word from your loop, no need to index the vector. 只需从循环中打印单词即可,无需索引向量。
for(int i=0;i<word.length(); i++)
{
if(!isalpha(word[i]))
{
name.push_back(word);
cout << "Found word: " << word << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.