2013-07-16 53 views
2

我試圖在用戶輸入中出現字母'a'時增加數組(alphabet[0])索引,但是當我打印出alphabet[0]時,我收到錯誤的輸出。遞增數組

例題:

"Enter a string" 

adam //input 

2665453 //printed on screen 
2665453 
2665453 
2665453 
2665453 

輸出我試圖實現應該是2號,在亞當2「一的。

這裏是我的代碼:

class Counter { 

    public: 
     string input; //the string used for user input 
     int alphabet[26]; 
     int numbers[10]; 
    void countcharacters(); 
    void countnumbers(); 

    private: 
}; 

void Counter::countcharacters() { 
    cout << "Enter a string" <<endl; 
    getline(cin, input); 

    for(int i=0; i<input.length(); i++) { 
     if(input.at(i) == 'a'){ 
      alphabet[0]++; 
     } 
    cout << alphabet[0] << endl; 
    } 
} 
+0

如果您只是想在屏幕上打印一個數字'2',那麼您會希望將該cout語句放在for循環之外。 – BrainSteel

+0

您需要將'alphabet'數組展開爲52以考慮小寫字母或使用'std :: tolower'或'std :: toupper'將這些字母轉換爲相同的大小寫。 –

+0

注意:一個字符串可以包含非字母字符,所以您應該查看'std :: isalpha'來確定字符是否是字母。 –

回答

8

這個問題很簡單。你的記憶是未初始化的。您的數組包含具有錯誤值的整數。在您的計數器類的構造函數中,將它們全部設置爲0.

您可以使用std :: fill在算法頭中找到它。它的文檔可以找到here

class Counter{ 

public: 
    Counter() 
    { 
     std::fill(std::begin(alphabet), std::end(alphabet), 0); // C++11 
     std::fill(alphabet, alphabet + 10, 0); // c++03 
    } 

    // The rest of your class goes here 
}; 

std::beginstd::end模板可以在迭代器頭中找到。

+1

正確,大多數語言默認初始化值爲零,但c語言不會。您的變量起始值將是用於定義值的內存位置中剩餘的值,最終會給您一個看似隨機的值。 – Lochemage

+0

謝謝你,先生,完美的工作。我很感激。 – PhDre

0

這裏也是控制輸入的例子,並存儲在每一個字符計數它計算爲:

//////////////////////////// 
// AlphaNumCounter.h 
//////////////////////////// 


#ifndef ALPHANUMCOUNTER_H 
#define ALPHANUMCOUNTER_H 
#include "stdafx.h" 
#include <vector> 
#include <map> 

namespace MyStuff 
{ 
const int NOT_VALID_SEARCH_CHAR = -1; 

class AlphaNumCounter 
{ 
public: 
    AlphaNumCounter(); 
    AlphaNumCounter(bool bIsCaseSensitive); 

    unsigned int CountOccurance(const std::string &haystack, const char &needle); 

    // Debug func that print all the occurances of a character on the last CountOccurance call 
    void PrintOccurances() 
    { 
     for(std::map<char, unsigned int>::iterator pIter = m_mapAlphaNumerics.begin(); pIter != m_mapAlphaNumerics.end(); pIter++) 
     { 
      char c = (*pIter).first; 
      int count = (*pIter).second; 

      std::cout << "'" << c << "' had '" << count << "' occurances on last count iteration." << std::endl; 
     } 
    } 

private: 
    void Init(); // Shared initializer for all ctor's 

    std::map<char, unsigned int> m_mapAlphaNumerics; // A map which holds the number of occurances of char (i.e: ['a'][7], if 'a' was found 7 times) 
    bool m_bIsCaseSensitive; // Should 'A' be counted as 'a', and vice versa...? 
}; 
} 

#endif // ALPHANUMCOUNTER_H 

///////////////////////////////// 
// AlphaNumCounter.cpp 
///////////////////////////////// 


#include "stdafx.h" 
#include "AlphaNumCounter.h" 
#include <algorithm> 

using namespace MyStuff; 

AlphaNumCounter::AlphaNumCounter() : m_mapAlphaNumerics(), m_bIsCaseSensitive(false) 
{ 
    Init(); 
} 
AlphaNumCounter::AlphaNumCounter(bool bIsCaseSensitive) : m_mapAlphaNumerics(), m_bIsCaseSensitive(bIsCaseSensitive) 
{ 
    Init(); 
} 

void AlphaNumCounter::Init() 
{ 
    // Store lowercase a - z 
    for(char i = 'a'; i <= 'z'; i++) 
     m_mapAlphaNumerics[i] = 0; 

    // Store uppercase a-z 
    for(char i = 'A'; i <= 'Z'; i++) 
     m_mapAlphaNumerics[i] = 0; 

    // Store 0 - 9 
    for(char i = '0'; i <= '9'; i++) 
     m_mapAlphaNumerics[i] = 0; 
} 

unsigned int AlphaNumCounter::CountOccurance(const std::string &haystack, const char &needle) 
{ 
    // If neither a-z || A-Z || 0-9 is being searched for, we return a indication of that. 
    if(m_mapAlphaNumerics.find(needle) == m_mapAlphaNumerics.end()) 
     return NOT_VALID_SEARCH_CHAR; 

    char ch = needle; 
    std::string sz = haystack; 


    // If the check is not case sensitive (i.e: A == a), we make sure both params are lowercase for matching. 
    if(!m_bIsCaseSensitive){ 
     ch = ::tolower(ch); 
     std::transform(sz.begin(), sz.end(), sz.begin(), ::tolower); 
    } 

    // Count occurances of 'ch' in 'sz' ('needle' in 'haystack') 
    std::size_t n = std::count(sz.begin(), sz.end(), ch); 

    // The occurances of 'needle' must be set to 'n' for this iteration 
    m_mapAlphaNumerics[ch] = n; 

    // Also set the uppercase val if its case insensitive. Then both 'a' and 'A' would have the same occurance count. 
    if(!m_bIsCaseSensitive) 
     m_mapAlphaNumerics[::toupper(ch)] = n; 

    return n; // Return the count for convenience of usage 
} 




////////////////////// 
// Main.cpp 
////////////////////// 


using namespace std; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    MyStuff::AlphaNumCounter aCounter; 
    aCounter.PrintOccurances(); 

    cout << "\n--------------------------------------------------------------\n"; 
    cout << "Enter a string: " << std::endl; 
    string haystack = string(); 
    getline(cin, haystack); 

    cout << "\nNow enter a single alphanumerical character to count, in that string: " << endl; 
    char needle; 
    cin >> needle; 
    cin.clear(); 
    cin.ignore(numeric_limits<streamsize> ::max(), '\n'); 

    while(aCounter.CountOccurance(haystack, needle) == MyStuff::NOT_VALID_SEARCH_CHAR) 
    { 
     cout << "\nI repeat: enter a single *alphanumerical* character to count, in that string: " << endl; 
     cin >> needle; 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize> ::max(), '\n'); 
    } 

    cout << "\n--------------------------------------------------------------\n"; 
    aCounter.PrintOccurances(); 

    system("PAUSE"); 
    return 0; 
} 

希望它能幫助! Regards, Oyvind