Reputation: 13
I am attempting to read in a file (input.txt) and go string by string and storing only the words in a vector (name). 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". 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. 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;
}
Upvotes: 0
Views: 122
Reputation: 18848
You're indexing the name
vector with the loop variables you're using to iterate the word
string. Since you have an if
statement there, it's entirely possible that name.push_back(word);
is never called, and immediately you're wrongly indexing into 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;
}
}
Upvotes: 1