C++ string 的== operator. 那我們就開始吧! C 語言的strcmp. C 語言要判斷c-style 字串是否相等通常會 ... ... <看更多>
strcmp c實作 在 [問題] strcmp的輸出怪怪的- 看板C_and_CPP | PTT數位生活區 的推薦與評價
餵入的資料(Input): struct {char str1[10], str2[10];} s; strcpy(s.str1, "yahoo"); strcpy(s.str2, "google"); ... p如何實作的 ... [問題] C語言初學觀念請益. ... <看更多>
strcmp c實作 在 [問題] strcmp (字串比對)實作- 看板C_and_CPP 的推薦與評價
開發平台(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
感謝,已修正,可是不知為何,只要輸入空格,執行的時候就會停頓
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
... <看更多>