分词错误-比较不同的单词在c++输入中出现的次数
segmentation fault - Compare how many times distinct words appear in inputs C++
我一直在尝试不同的技术来解决这个问题,而且我对c++或一般编程相当陌生。这个问题来自于我正在读的一本叫做"加速c++"的书,到目前为止我只读到了第三章,所以我只尝试用第三章教的东西来解决这个问题。当我运行程序时,它运行得很好,但只要我输入一个单词,我就会出现分割错误。有人能给我解释一下为什么会这样吗?此外,如果我的方法与我所知道的知识到目前为止是极其低效的,暗示一个更好的方法来做事情在章节的边界将是伟大的!
代码如下:
#include <iostream>
#include <algorithm>
#include <ios>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
//ask for the first sentence to be typed in.
cout << "Please enter some words: ";
vector<string> word_storage;
vector<int> word_count;
string x;
int y = 0;
//words inputed pushed into vector(word_storage) or incremented if they exist
while(cin >> x) {
for(int i = 0; i <= y; i++) {
if(x != word_storage[i]) {
word_storage.push_back(x);
word_count.push_back(1);
} else {
word_count[i] += 1;
}
}
y++;
}
cout << endl;
//get size of word_storage
typedef vector<double>::size_type vec_sz;
vec_sz size = word_storage.size();
//system prints how many of each word exist
for(int j = 0; j <= size; j++) {
cout << "There are: " << word_count[j]
<< " of the word " << word_storage[j];
}
cout << endl;
return 0;
}
注:我提前为这些难看的代码道歉。
向量包含自己的大小。我相信你可能有两个bug。首先,如果for循环中的'<='要从vector的末尾移走,它应该是'<'。第二,当你没有向word_storage中添加单词时,你在迭代y。
我认为你的发现部分应该看起来更像:
while(cin >> x) {
for(int i = 0; i < word_storage.size(); i++) {
if(x != word_storage[i]) {
word_storage.push_back(x);
word_count.push_back(1);
} else {
word_count[i] += 1;
}
}
}
还可以进行其他一些改进,其中最重要的是使用结构体将存储和计数绑定到同一个vector,并使用迭代器。
for(int i = 0; i <= y; i++) {
if(x != word_storage[i]) {
word_storage
是一个未初始化的空向量。而你试图访问一个空向量会导致分割错误。例如,在循环开始时,vector容器中没有可对其进行下标操作的对象。
如果word_storage
的大小大于i
,则对[]
进行操作
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type