2014-06-24 6 views
0

"C Primer Plus"책의 연습 문제를 쓰려고합니다. 그들 중 한 명은 내가 해결할 수 없거나 진행 상황을 파악할 수 없었습니다. (필요에 따라)문자열의 첫 번째 문자는 어디에 있습니까?

#include <stdio.h> 

    int main() 
    { 
     char str[500]; 
     gets(str); 
     puts(str); 

     return 0; 
    } 

출력 : 단계별 시련을 디버깅 후, 난 그냥이 테스트

정확한 LY 모든 것은 내가

를 입력

내가 입력 정확한 LY 모든 것

하지만 운동하려는 것에 대해서는 2 개 이상의 연속 된 공백에 민감합니다. gets() 다음에 puts()이옵니다. 그러나 나는 무엇이 잘못되었는지를 모른다.

/* 
BUG: MORE THAN 1 SPACES NEXT TO EACHOTHER. WHERE THE FIRST CHARACTER GOES?!! 

Write a function that takes a string as an argument and removes the spaces from the string. 
Test it in a program that uses a loop to read lines until you enter an empty line. 
The program should apply the function to each input string and display the result. 
*/ 

#include <stdio.h> 
#include <string.h> 

int spaceRemover(char *in); 
void takeBack(char *in); 

int main(void) 
{ 
    puts("Enter a string for the SPACE-REMOVER: (RETURN to quit)"); 
    do 
    { 
     char str[500]; 
     int spaces; 
     gets(str); 
     puts(str); //for debugging to know is it complete just after gets() ? 
     //printf("\nFirst char of string: %c\n",str[0]); 
     //printf("\nFirst Char: %p '%c'\n",str,*str); 
     spaces=spaceRemover(str); 
     printf("\n%d spaces removed: \n",spaces); 
     puts(str); 
     puts("\nEnter a string for the SPACE-REMOVER: (RETURN to quit)"); 
    } 
    while (getchar() != '\n'); 

    return 0; 
} 

int spaceRemover(char *in) 
{ 
    int count=0, i; 
    for (i=0 ; i<strlen(in) ; i++) 
     while (*(in+i)==' ')  //IF will skip more than one space; but WHILE won't 
     { 
      //printf("%p '%c' \t B4: %p '%c'\n",in+i,*(in+i),in+i-1,*(in+i-1)); 
      takeBack(in+i); 
      count++; 

     } 
    return count; 
} 

void takeBack(char *spaceLocation) 
{ 
    int j=0; 
    while (*(spaceLocation+j)!= '\0') 
    { 
     *(spaceLocation+j) = *(spaceLocation+j+1); 
     //putchar(*(spaceLocation+j+1)); 
     j++; 
    } 

    return; 
} 

출력 :

Enter a string for the SPACE-REMOVER: (RETURN to quit) 

this is separated by single spaces 

this is separated by single spaces 


5 spaces removed: 

thisisseparatedbysinglespaces 


Enter a string for the SPACE-REMOVER: (RETURN to quit) 

I'll try more than single space separators 

'll try more than single space separators 

13 spaces removed: 

'lltrymorethansinglespaceseparators 

참고 :이 하나를 사용하여 인용구를 사용하여이 연속 공간을 폐기 그래서 전체 코드를 인용.

여기에 무슨 일이 있습니까? 내 코드에 문제가 있습니까?

(GCC와 코드 :: 블록을 사용.) 문자열의 첫 번째 문자가가는

+2

디버거가 작동하는 데 걸리는 시간. 모든 코드를 게시하고 "도움"을 요청하는 것은 버그가 수정 된 방법이 아닙니다. –

+0

감사합니다. 나는 프로그래머를 얻는 것에 대한 어떤 조언도 환영한다. 나는 GDB를 시작하는 것으로 생각한다. – pedyram

답변

0

를?

첫 번째 문자는 getcharwhile (getchar() != '\n');입니다. 당신이 문자열을 입력하면

I'll try more than single space separators 

은 다음 첫 번째 문자 Igetchar에 의해 읽고 \n에 비교됩니다. 따라서, gets 판독하는 입력 버퍼에서만

'll try more than single space separators  

을 뒤에 남겨. 에 main 몸을 변경 : 당신의 getchar()은 표준 입력에서 문자를 기대 시작

char str[500]; 
    puts("Enter a string for the SPACE-REMOVER: (RETURN to quit)"); 
    gets(str); 
    do 
    { 
     int spaces; 
     puts(str); //for debugging to know is it complete just after gets() ? 
     //printf("\nFirst char of string: %c\n",str[0]); 
     //printf("\nFirst Char: %p '%c'\n",str,*str); 
     spaces=spaceRemover(str); 
     printf("\n%d spaces removed: \n",spaces); 
     puts(str); 
     puts("\nEnter a string for the SPACE-REMOVER: (RETURN to quit)"); 
     gets(str); 
    } 
    while (str[0]); 
0

그래서 문제는 루프 내부

puts("\nEnter a string for the SPACE-REMOVER: (RETURN to quit)"); 

말할 때 루프의 종료 조건, 즉 함께하고 문자열을 입력 시작하는 문자열의 첫 번째 문자가 제공됩니다. 따라서 다음 반복에서 str은 첫 번째 문자가 없으며 예상 한 것과 다릅니다.

그래서 코드가 요구 사항 즉 빈 문자열까지

입력 문자열을 입력하지

에 따라 작업을 확인합니다.

PRO 정보 : gets는 위험한 일상을 사용하지 마십시오. fgets를 대신 사용하십시오. 자세히보기 here

메인 루틴의 루프를 다음과 같이 변경하십시오.

do 
    { 
     int spaces; 
     //for debugging to know is it complete just after gets() ? 
     //printf("\nFirst char of string: %c\n",str[0]); 
     //printf("\nFirst Char: %p '%c'\n",str,*str); 
     spaces=spaceRemover(str); 
     printf("\n%d spaces removed: \n",spaces); 
     puts(str); 

     puts("\nEnter a string for the SPACE-REMOVER: (RETURN to quit)"); 
     gets(str); 
     puts(str); 
    } 
    while (strcmp(str,"")); 
+0

팁을 고맙게 생각합니다. – pedyram

관련 문제