好,所以我不确定是什么导致我收到错误
分段错误(核心已转储)
但是我每次运行程序时都会得到它。如果有人可以解释我在做什么错,那太好了。
#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或类似的东西)而引起的,但是我终生无法找到我自己的代码中的错误。如果您可以为我提供任何帮助,请