我正在做一个介绍 C++ 的作业,我必须读取一个字符串,然后计算字符串本身中字母的频率,并输出结果。我不允许修改我的任何函数头(如果可以的话,我现在可能不会在这里),而且我看到大部分更困难的部分都已关闭。我得到的唯一问题是我以前能够读取我的字符串,但我的程序无法正确计算第一个字符的出现。在我修复它之后,我在读取字符串的函数中出现了分段错误。到目前为止,我的代码是这样的:
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
//FUNCTION PROTOTYPES
string getPhrase(const string & prompt);
int charIndex(const vector<char> & list, char letter);
void addLetter(vector<char> & letters, vector<int> & freqs, char letter);
int main()
{
// Define your local variables
const int COLUMNWIDTH = 2; //will be used in later functions
vector<char> letters; //list of letters in the string
vector<int> freqs; //corresponding list of frequencies of letters
vector<char> list; //not so sure whats up with this, but it
char letter; //the current letter
int index =-1; //index location of letter, if == -1, then letter is not currently indexed and needs to be
string prompt; //user input statement
//Input string
const string phrase = getPhrase(prompt);
int i =0;
while (phrase[i] == ' ')//determine first term of phrase that isn't a space, then make that space the first term of list so next loop can run
{
i++;
}
list[0] = phrase[i];
for (int i = 0; i<phrase.length(); i++)
{
index = charIndex(list,phrase[i]);
if (phrase[i]!= ' ')
{
if (index == -1)
{
letter = phrase[i];
addLetter(letters, freqs, letter);
list = letters;
index = charIndex(list,letter);
}
}
}
return 0;
}
// FUNCTION DEFINITIONS GO HERE:
string getPhrase(const string &prompt)
{
string phrase;
std::cout<<"Enter phrase: "; //**ERROR IS OCCURING HERE **
std::getline(cin, phrase); //**ERROR IS OCCURING HERE **
return phrase;
}
//determine the index location of the specific letter
int charIndex(const vector<char> &list, char letter)
{
int i = 0;
int index = -1;
while ( i <= list.size())
{
if (letter == list[i])
{
index = i;
if (index != -1)
{
i = list.size() +1;
}
}
i++;
}
return (index);
}
//addLetter adds the new letter to the list of letters, and the corresponding frequency list is changed
void addLetter(vector<char> & letters, vector<int> & freqs, char letter)
{
letters.push_back(letter);
freqs.push_back(1);
}
我希望我能够删除很多“const”,但我不能。我也经历过并确定错误发生在我的“getLine”的“getPhrase”函数中,并且不知道是什么原因造成的。