2013-07-16 2 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

문제는 매우 간단합니다 :

여기 내 코드입니다. 메모리가 초기화되지 않았습니다. 배열에 값이 잘못된 int가 들어 있습니다. 카운터 클래스의 생성자에서 모두 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

정확함. 대부분의 언어는 기본적으로 값을 0으로 초기화하지만 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; 
} 

는 희망이 도움이! 감사합니다, Oyvind