我正在尝试读入一个文件 (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/