【发布时间】:2015-04-09 19:52:57
【问题描述】:
好的,所以我在这里遇到了一些问题。问题是这段代码可以在朋友的计算机上运行,但是当我尝试运行它时出现分段错误。
我正在阅读一个看起来像这样的文件:
word 2 wor ord
anotherword 7 ano oth the her erw wor ord
...
我想解析文件的每个单词。前两个单词(例如 word 和 2)将被删除,但在此过程中将第一个单词保存在另一个变量中。
我已经环顾四周来完成这个,我想出了这段半途而废的代码,它似乎可以在我朋友的计算机上运行,但不适用于我的计算机。
Dictionary::Dictionary() {
ifstream ip;
ip.open("words.txt", ifstream::in);
string input;
string buf;
vector<string> tokens; // Holds words
while(getline(ip, input)){
if(input != " ") {
stringstream ss(input);
while(ss >> buf) {
tokens.push_back(buf);
}
string werd = tokens.at(0);
tokens.erase(tokens.begin()); // Remove the word from the vector
tokens.erase(tokens.begin()); // Remove the number indicating trigrams
Word curr(werd, tokens);
words[werd.length()].push_back(curr); // Put the word at the vector with word length i.
tokens.clear();
}
}
ip.close();
}
在文件中解析这种结构并删除前两个元素但保存其他元素的最佳方法是什么?如您所见,我正在制作一个 Word 对象,其中包含一个字符串和一个向量供以后使用。
问候
编辑;似乎可以很好地添加第一行,但在删除第二个元素时,它会因分段错误错误而崩溃。
编辑; words.txt 包含以下内容:
addict 4 add ddi dic ict
sinister 6 ini ist nis sin ste ter
test 2 est tes
cplusplus 7 cpl lus lus plu plu spl usp
没有前导空格或结尾空格。并不是说它一直都在读。
Word.cc:
#include <string>
#include <vector>
#include <algorithm>
#include "word.h"
using namespace std;
Word::Word(const string& w, const vector<string>& t) : word(w), trigrams(t) {}
string Word::get_word() const {
return word;
}
unsigned int Word::get_matches(const vector<string>& t) const {
vector<string> sharedTrigrams;
set_intersection(t.begin(),t.end(), trigrams.begin(), trigrams.end(), back_inserter(sharedTrigrams));
return sharedTrigrams.size();
}
【问题讨论】:
-
从文件开头读取一个空行很容易弄乱程序。与其将很多东西推到一个向量上然后删除其中两个,我建议一开始就不要推它们。
-
@chris 你又来了,尝试用简单的方法做事=P(uptick)
-
单词数组的类型/大小?
-
The thing is this code works on a friend's computer but I'm getting segmentation faults when I try to run it.好吧,问题不在于您的计算机。欢迎来到“未定义行为”的世界。 -
@PaulMcKenzie,谢天谢地,你在电脑商店的收银台上发现了我。
标签: c++ string parsing getline