[問題] strcmp (字串比對)實作

看板C_and_CPP作者 (沒有存在感的人)時間9年前 (2015/06/09 16:23), 9年前編輯推噓2(205)
留言7則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) lubuntu + gcc 4.9.2 問題(Question): 我比較"abcd"跟"efgh"結果是"They are different!" 可是若是我打"abcd"跟"abcd " (後者多一空格) 或"ab cd"跟"abcd" 結果是"They are the same!" 請問該如何解決他不認得空格的問題? 謝謝 餵入的資料(Input): ab cd 與 abcd 預期的正確結果(Expected Output): "They are different!" 錯誤結果(Wrong Output): "They are the same!" 程式碼(Code):(請善用置底文網頁, 記得排版) 全部程式碼在此: https://gist.github.com/gnitnaw/127d36d1eca96f431ef9 或看以下程式碼(跟上面的link一樣): #include <stdio.h> #define MAXSIZE 80 void strcomp(char* p1, char* p2); void read_string(char *pt); int main(void) { char line1[MAXSIZE], line2[MAXSIZE]; printf("Enter first string : "); read_string(line1); printf("%s\n", line1); printf("Enter second string : "); read_string(line2); printf("%s\n", line2); strcomp(line1, line2); return 0; } void read_string(char *pt) { int i; for(i=0; i < MAXSIZE; i++) { if (getchar() != '\n') { pt[i] = getchar(); } else { break; } } } void strcomp(char* p1, char* p2) { while (*p1 == *p2) { if (*p1 == '\0' || *p2 == '\0') { break; } ++p1; ++p2; } if (*p1 == '\0' && *p2 == '\0') { printf("They are the same! \n"); } else { printf("They are different! \n"); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.41.134.196 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1433838235.A.BFD.html

06/09 16:27, , 1F
跟空格無關, 是你把 ++p1 寫成 ++*p1 了
06/09 16:27, 1F

06/09 16:27, , 2F
所以若第一個字一樣, 就會一直迴圈直到 overflow 最後
06/09 16:27, 2F

06/09 16:28, , 3F
變成0才停止
06/09 16:28, 3F
感謝,已修正,可是不知為何,只要輸入空格,執行的時候就會停頓 Enter first string : ab cd (Enter後程式停頓,要再按Enter才會繼續) bc -> 輸出錯誤(用printf("%s\n")) Enter second string : abcd bd -> 也是輸出錯誤 They are different! 請問這是哪裡有問題呢?感謝 ※ 編輯: wtchen (90.41.134.196), 06/09/2015 16:45:11

06/09 17:33, , 4F
read_string 的時候同一字元 getchar 兩次. 其他的就...
06/09 17:33, 4F

06/09 17:52, , 5F
剛剛我也想到了!感謝
06/09 17:52, 5F

06/09 21:29, , 6F
建議字串初始化,read_string結尾補\0
06/09 21:29, 6F

06/09 23:31, , 7F
這個我也想到了,感謝,好久沒玩字串了
06/09 23:31, 7F
文章代碼(AID): #1LTgARlz (C_and_CPP)