from http://blog.csdn.net/david_xtd/article/details/14644011
2013.11
問題:
源代碼由C++代碼轉(zhuǎn)化而來,所以對(duì)于C風(fēng)格字符串的比較,仍然使用C++中比較C風(fēng)格字符串的方式
- char* pstr = "enable";
- if (pstr == "enable") {
- PerformTask();
- }
但在程序運(yùn)行的時(shí)候,發(fā)現(xiàn)PerformTask()始終沒有被調(diào)用到。
解決辦法:
1. 在C++中,問題中所用的字符串比較方式是可行的。
在C中,該種字符串比較方式具有很大的欺騙性和殺傷力,因?yàn)?,程序編譯也能通過,但實(shí)際上所比較的條件總不能成立,所以條件成立后所執(zhí)行的操作總不能完成;
2. 為了防止這類錯(cuò)誤在C語言中出現(xiàn),自己編譯測(cè)試程序的時(shí)候應(yīng)該把Wall選項(xiàng)打開,這樣,編譯的時(shí)候會(huì)有錯(cuò)誤提示;
- u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$ gcc -Wall -std=gnu99 -o test_strtok test_strtok.c
- test_strtok.c: In function ‘main’:
- test_strtok.c:49:16: warning: comparison with string literal results in unspecified behavior [-Waddress]
- u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$
提示應(yīng)該使用正確的字符串處理方式。
3. 示例代碼:
- #include <stdio.h>
- #include <string.h>
-
- int main() {
- printf("\n========================================================================\n");
- char str1[] = "1/6";
- char* delim1 = "/";
- char* seq_no = NULL;
- char* total_no = NULL;
- seq_no = strtok(str1, delim1);
- printf("seq_no is: %s\n", seq_no);
- total_no = strtok(NULL, delim1);
- printf("total_no is: %s\n", total_no);
- // if (seq_no == "1") {
- if (!strcmp(seq_no, "1")) {
- printf("This is seq number %s\n", seq_no);
- }
-
- return 0;
- }
運(yùn)行結(jié)果:
- u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$ ./test_strtok
-
- ========================================================================
- seq_no is: 1
- total_no is: 6
- This is seq number 1
- u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$
問題解決。
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。