文字列を読み取ってから、文字列自体の文字の頻度を数え、結果を出力する必要があるイントロ 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」関数でエラーが発生していることも確認しましたが、何が原因なのかわかりません。