2012-09-07 3 views
-5

저는 텍스트 문서의 글자 수를 세는 프로그램을 C++로 만들고 있습니다. 내가 뭘 잘못하고 있는지 알 필요가있어, 나는 결과에 미친 숫자를 얻고있다. 나는 지난 번에 좋은 도움을 받았고, 카운트 후 "주파수 [?]"를 입력했습니다. 계산 자체에 문제가 있지만 무엇을해야합니까? 그들은 제로가 아닌 상수 char 값 때문에 이러한 조건문의글자 카운터에 잘못된 결과가 나타납니다.

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

const int ALPHA_SIZE = 26; 

void open_file (ifstream &); 

void process (ifstream &, int [], string lineBuffer); 

void draw (int []); 

void printchar (int[]); 

string lineBuffer; 


int main() 
{ 
    string lineBuffer; 
    ifstream infile; 
    open_file (infile); 

    int frequency [ALPHA_SIZE]; 

    process (infile, frequency, lineBuffer); 
     draw (frequency); 


    system("Pause"); 
    return 0; 
} 

void open_file (ifstream & inf) 
{ 
    char infilename[50]; //actual file name 
    cout << "File name for input? "; 
    cin >> infilename; 
    inf.open(infilename); 
} 

void process (ifstream &infile, int frequency[], string lineBuffer) 
{ 

    int A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z; 
    A = 0; 
    B = 0; 
    C = 0; 
    D = 0; 
    E = 0; 
    F = 0; 
    G = 0; 
    H = 0; 
    I = 0; 
    J = 0; 
    K = 0; 
    L = 0; 
    M = 0; 
    N = 0; 
    O = 0; 
    P = 0; 
    Q = 0; 
    R = 0; 
    S = 0; 
    T = 0; 
    U = 0; 
    V = 0; 
    W = 0; 
    X = 0; 
    Y = 0; 
    Z = 0; 
    if (infile.is_open()) 
    { 

     while(getline(infile, lineBuffer)) 

     { 

     if ('a' || 'A') 
      { A++; 
      } 
     if ('b' || 'B') 
      { B++; 
      } 
     if ('c' || 'C') 
      { C++; 
      } 
     if ('d' || 'D') 
      { D++; 
      } 
     if ('e' || 'E') 
      { B++; 
      } 
     if ('f' || 'F') 
      { F++; 
      } 
     if ('g' || 'G') 
      { G++; 
      } 
     if ('h' || 'H') 
      { H++; 
      } 
     if ('i' || 'I') 
      { I++; 
      } 
     if ('j' || 'J') 
      { J++; 
      } 
     if ('k' || 'K') 
      { K++; 
      } 
     if ('l' || 'L') 
      { L++; 
      } 
     if ('m' || 'M') 
      { M++; 
      } 
     if ('n' || 'N') 
      { N++; 
      } 
     if ('o' || 'O') 
      { O++; 
      } 
     if ('p' || 'P') 
      { P++; 
      } 
     if ('q' || 'Q') 
      { Q++; 
      } 
     if ('r' || 'R') 
      { R++; 
      } 
     if ('s' || 'S') 
      { S++; 
      } 
     if ('t' || 'T') 
      { T++; 
      } 
     if ('u' || 'U') 
      { U++; 
      } 
     if ('v' || 'V') 
      { V++; 
      } 
     if ('w' || 'W') 
      { W++; 
      } 
     if ('x' || 'X') 
      { X++; 
      } 
     if ('y' || 'Y') 
      { Y++; 
      } 
     if ('z' || 'Z') 
      { Z++; 
      } 
      } 
     infile.close(); 
     frequency [0] = A; 
     frequency [1] = B; 
     frequency [2] = C; 
     frequency [3] = D; 
     frequency [4] = E; 
     frequency [5] = F; 
     frequency [6] = G; 
     frequency [7] = H; 
     frequency [8] = I; 
     frequency [9] = J; 
     frequency [10] = K; 
     frequency [11] = L; 
     frequency [12] = M; 
     frequency [13] = N; 
     frequency [14] = O; 
     frequency [15] = P; 
     frequency [16] = Q; 
     frequency [17] = R; 
     frequency [18] = S; 
     frequency [19] = T; 
     frequency [20] = U; 
     frequency [21] = V; 
     frequency [22] = W; 
     frequency [23] = X; 
     frequency [24] = Y; 
     frequency [25] = Z; 


    } 
} 

void draw(int frequency[]) 
{ 
    cout << "A:" << frequency[0] << endl; 
    cout << "B:" << frequency[1] << endl; 
    cout << "C:" << frequency[2] << endl; 
    cout << "D:" << frequency[3]<< endl; 
    cout << "E:" << frequency[4] << endl; 
    cout << "F:" << frequency[5] << endl; 
    cout << "G:" << frequency[6] << endl; 
    cout << "H:" << frequency[7] << endl; 
    cout << "I:" << frequency[8] << endl; 
    cout << "J:" << frequency[9] << endl; 
    cout << "K:" << frequency[10] << endl; 
    cout << "L:" << frequency[11] << endl; 
    cout << "M:" << frequency[12] << endl; 
    cout << "N:" << frequency[13] << endl; 
    cout << "O:" << frequency[14] << endl; 
    cout << "P:" << frequency[15] << endl; 
    cout << "Q:" << frequency[16] << endl; 
    cout << "R:" << frequency[17] << endl; 
    cout << "S:" << frequency[18] << endl; 
    cout << "T:" << frequency[19] << endl; 
    cout << "U:" << frequency[20] << endl; 
    cout << "V:" << frequency[21] << endl; 
    cout << "W:" << frequency[22] << endl; 
    cout << "X:" << frequency[23] << endl; 
    cout << "Y:" << frequency[24] << endl; 
    cout << "Z:" << frequency[25] << endl; 

} 
+0

배열 및 루프를 사용하면 입력 한 내용을 모두 저장할 수 있습니다. –

+0

'a'|| 'A'-> 참, 'b'|| 'B'-> 사실 ... 이것은 갈아 치울 것입니다 – sehe

+0

무엇이 문제입니까? 그리고 어디? 당신이 "또 다른 실수를 저질렀다"고 말하면 질문하지 않습니다. – jalf

답변

3

각각

if ('n' || 'N') 

항상 true로 평가합니다. 따라서 계산에 사용하는 변수는 항상 증가합니다. 캐릭터의 출현 빈도를 테스트하려면 다음과 같은 것이 필요합니다.

char char_to_test; 
if (char_to_test == 'n' || char_to_test == 'N') { 
    N++; 
} 

현재 카운트를 늘리십시오. 또한 테스트를 수행하려면 실제로 파일에서 각 문자를 추출해야합니다. getline에서 string을 얻은 후에는 개별 문자를 반복하여 위와 같이 테스트해야합니다.

+0

잘 모르겠다면 이것은 두 번째 학기에 불과하며 더 이상 DarkGDK를 가르치지 않아서 다시 공부해야합니다. –

+0

문자열에서 각 문자를 추출하고 원하는 문자와 같으면 TEST를 추출해야합니다. 테스트는 단지이'if ('n'! = 0 || 'N'! = 0)'을 지금하고 있습니다. 분명히 그들은 결코 0이 아니므로 if 블럭 안의 각 문장이 실행됩니다. 상관 없습니다. – mathematician1975

0

프로그램에 각 문자를 한 번만 읽도록하는 것은 없습니다. 이것은이 문제와 유사합니다. http://www.cplusplus.com/forum/beginner/24492/ 언제 끝내야하는지 프로그램에 알려야합니다. 프로그램에 묻는 것은 "A가 파일 A ++에 존재하는 동안"입니다. 항상 파일에 존재합니다. 당신은 이것을 할 수 있습니다 : http://www.cplusplus.com/reference/iostream/istream/get/

이것은 char, char을 통해 파일을 압축하는 데 도움이됩니다. 당신은 여전히 ​​파일의 끝에서 그것을 멈추게하는 방법을 알아 내야 만합니다.

+0

이제 문자가 무엇이든간에 문자 테스트를 사용하여 테스트합니다. 그래서 미친 숫자는 모든 것에 동의하는 프로그래밍 때문입니다. –

0

나는 너를 게으른 자세로 작업해야한다고 생각한다. 다음은 C의 버전입니다 : 내가 (예를 들어, 대신 파일을 여는 stdin의 읽기) 조금 단순화했습니다

unsigned counts[UCHAR_MAX]; 

int main() { 
    int ch; 

    while (EOF != (ch=getchar())) 
     ++counts[toupper((unsigned char)ch)]; 

    for (int i=0; i<UCHAR_MAX; i++) 
     if (isupper(i)) 
      printf("%c: %u\n", i, counts[i]); 

    return 0; 
} 

는, 그러나 이것은 궁극적으로 아주 간단한 일이다 - 금주 모임을 만들려고하지 않는다 훨씬 더 복잡합니다.

+0

죄송합니다. 이해가 안됩니다. C, 저는 C++을 배우고 있습니다. –

1

코드에 많은 문제가 있습니다.

그 중 하나는 파일을 여는 함수를 호출한다는 것입니다. 그것의 범위가 없어 일단

void open_file (ifstream & inf)

이 기능은 파일을 닫을 것이다.

모든 변수에는 반복적 인 코드가 많으므로 루프를 사용하면 쉽게 작성할 수 있습니다.

#include <string> 
#include <iostream> 
#include <algorithm> 
#include <fstream> 
#include <cctype> 
#include <map> 

int main() { 
    std::map<char,int> alpha; 
    //Fills the map with A-Z with 0 as the value. 
    for(char k = 65; k <= 90; k++) { 
     alpha.insert(std::pair<char,int>(k,0)); 
    } 
    //opens example.txt contains "the quick brown fox jumped over the cow" 
    std::ifstream in("example.txt"); 
    std::string str; 
    if(in.is_open()) { 
     //loops through every line in the file. 
     while(std::getline(in,str)) { 
      //removes all whitespace 
      str.erase(std::remove_if(str.begin(),str.end(), ::isspace),str.end()); 
      //capitalizes the string 
      std::transform(str.begin(),str.end(),str.begin(), ::toupper); 
      //loops through the string 
      for(auto& i : str) { 
       if(isalpha(i)) 
        alpha[i]++; //Increments the frequency. 
      } 
     } 
    } 
    for(auto& i : alpha) 
     std::cout << i.first << " " << i.second << std::endl; 
} 
관련 문제