【发布时间】:2019-11-25 20:58:23
【问题描述】:
好的,所以我不确定是什么导致我收到错误
分段错误(核心转储)
但我每次运行程序时都会得到它。如果有人可以解释我做错了什么,那就太好了。
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
void frequency(char* paragraph, string words[],int num_words){
//Declare the required variables.
string temp = "";
int freq[num_words];
//Start the loop to set the frequency of each word to 0.
for(int i=0;i<num_words;i++){
freq[i] = 0;
}
//Start the loop to traverse the paragraph.
for(int i=0;i<=strlen(paragraph);i++){
//Check the string if a space or null is found.
if(paragraph[i] == ' ' || paragraph[i] == '\0'){
//Start the loop to compare each word.
for(int j=0;j<num_words;j++){
int flag = 0;
//Start the loop to comapare the word.
for(int k=0;k<words[j].length();k++){
//Convert both the characters to lowercase to compare ignoring the case.
if(tolower(temp[k]) != tolower(words[j].at(k))){
//Break the loop if the character does not match.
flag = 1;
break;
}
}
//Increase the frequency if the word matches with the current string.
if(flag == 0)
freq[j]++;
}
//Reset the string.
temp = " ";
}
//Otherwise, append the character in the string.
else{
temp = temp+paragraph[i];
}
}
//Start the loop to print the frequency of each word.
for(int i=0;i<num_words;i++){
cout<<words[i]<<": "<<freq[i]<<endl;
}
}
int main()
{
char *paragraph;
string *words;
string swords;
cout << "Enter the paragraph: ";
cin.getline(paragraph, 250);
cout << "Enter the words to search: ";
getline(cin, swords);
int spaces = 0;
//Start the loop to count the number of words.
for(int i = 0; i < swords.length(); i++){
if(swords.at(i) == ' ')
spaces++;
}
int num_words = spaces + 1;
int pos = 0;
string temp = " ";
//Create an array of strings to store the words.
words = (string*) new string[num_words];
//Start the loop to store the words in the array.
for(int i = 0; i < swords.length(); i++)
{
//Store the string in the array if a space is encountered.
if(swords.at(i) == ' ')
{
words[pos] = temp;
temp = " ";
++pos;
}
//Otherwise, append the character in the string.
else
{
temp += swords.at(i);
}
}
//Store the last string in the array.
words[pos] = temp;
//Call the function to compute and display the frequency.
frequency(paragraph, words, num_words);
//Return 0 and exit the code.
return 0;
}
我知道分段错误的发生主要是因为您试图访问您无权访问的内存(通常通过将变量设置为 null 或类似的东西)但我终生无法找到我自己的代码中的错误。如果你能提供任何帮助,请做
【问题讨论】:
-
你能提供你提供给程序的输入,以及你在seg错误之前得到的所有输出吗?
-
cin.getline(paragraph, 250);- 段落没有指向任何地方,您使用的是未初始化的指针。为什么指定paragraph可以容纳 250 个字符? -
仅供参考,要获得 C++ 中单词的频率计数大约需要 5 行代码——如果您愿意编写 C++ 而不是 C 并进行一些语法更改。
-
既然已经在使用
std::string,为什么还要使用 char 数组和 char 指针? -
好的,我将如何用 5 行代码编写这段代码?我是一名全新的计算机科学专业学生,我只想学习。我正在使用 char 数组,因为这是分配所需要的