2012-10-04 3 views
1

사용자가 입력 한 문자 수를 세어 인쇄하십시오. 배열을 사용할 수 없으며 사용자가 종료해야합니다. 나는 이것이 무엇이 잘못되었는지 전혀 모른다. 어떤 팁?C로 일련의 문자 계산하기

#include <stdio.h> 

int main(int argc, char *argv[]) 
{ 
    int input; 

    printf("Enter a series of characters:\n"); 

    input = getchar(); 

    while (input != EOF) 
    { 
    input++; 
    input = getchar(); 
    } 

    printf("You entered %d characters.\n", input); 

    return 0; 

} 

답변

4

은 현재의 입력, 또는 당신이 읽은 문자 수를 유지하기 위해 당신이 input을하려고 했습니까? 당신은 현재 두 가지 모두에 사용하려고 시도하는 것 같지만, 하나 또는 둘 다를 가질 수 있습니다.

3

입력 변수 input도 카운터로 사용됩니다.

+1

감사합니다, 나는 이상한 템플릿을 다음되었다. 나는 그것을 지금 모두 분류했다! –

+0

@ 닛키 : 아직 답변을 수락 했습니까? –

2

당신은 다른 두 가지의 input 변수를 사용하고 있습니다 :

  • stdin
  • 에서 다음 문자를 얻기 위해 문자의 총 수를 입력 계산.

첫 번째 사용은 두 번째 문자를 망칠 수 있습니다. input을 사용하여 다음 문자를 저장하면 문자 수를 덮어 씁니다.

두 가지 다른 목적으로 두 가지 변수가 필요합니다.

int input; 
int characterCount = 0; 

// your loop: 
    characterCount++; 
    input = getchar(); 
1

댓글 인라인

#include <stdio.h> 

int main(int argc, char *argv[]) 
{ 
    int input; 

    printf("Enter a series of characters:\n"); 

    input = getchar(); 

    while (input != EOF) 
    { 
/* Good so far - you have read a char from the user */ 
    input++; 
/* Why are you increment the user entered char by 1 - you need a separate counter */ 
    input = getchar(); 
/* Now you read another char from the user (to be mangled on next loop iteration */ 
    } 

    printf("You entered %d characters.\n", input); 

    return 0; 

}