我正在開發一個介紹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);
}
有很多的「常量」我希望我能夠刪除,但我不能。我也經歷了,並確定這個錯誤發生在我的「getLine」的「getPhrase」函數中,並且不知道是什麼導致了它。因爲雖然你宣佈list
作爲載體,你有沒有實際分配的任何元素還,所以[0]
不存在
list[0] = phrase[i];
:
事情通常是一個很好的理由'const',它是在你最感興趣的學習,以紀念這一切應該是'適當const'。 – Aesthete 2013-04-11 00:47:25
'字符串提示符'的用途是什麼,它在'字符串getPhrase(const string&prompt)'中用作參數?你似乎沒有做任何事情。 – JBentley 2013-04-11 01:46:52