카테고리 없음

[씨] C에서 사용자가 입력 줄 내 공간 수를 찾는 방법은 무엇입니까?

행복을전해요 2021. 3. 1. 00:09
int countspaces(const char *str)
{
  int count = 0 ;
    char c ;
      while((c = *str++) != 0)
        {
            if (c == ' ')
                  count++ ;
                    }
                    
                      return count ;
                      }
                      
                      ...
                      scanf (" %[^\n]s", &line[0])
                      int nbofspaces = countspaces(line) ;
                      
-------------------

입력을 성공적으로 읽을 수 있다면 다음과 같이 공백을 계산할 수 있습니다.

uint spaces = 0;
size_t len = strlen(line);
for (size_t idx=0; idx<len; ++idx)
   if (line[idx] == ' ')
         ++spaces;
         

그리고 BTW, 다음 스레드를 살펴보십시오.

scanf-> ANSI C를 사용한 최대 문자열 길이

sscanf를 정확하고 안전하게 사용하는 방법

scanf는 최고의 친구가 아닙니다.

-------------------

다음 프로그램은 문자열의 공백 수를 인쇄합니다.

    #include<stdio.h>
    void main(void)
        {
                char *input_string;
                        unsigned int space_counter = 0;
                                scanf("%[^\n]",input_string);
                                        while(input_string != '\0')
                                                {
                                                           if(*input_string == ' ')//check whether the char is space
                                                                         space_counter++      //increment space counter
                                                                         
                                                                                    input_string++;         //increment counter
                                                                                            }
                                                                                                    printf("Number of spaces in the string=%d",space_counter);
                                                                                                        }
                                                                                                        


출처
https://stackoverflow.com/questions/22089795