[英]Using strcmp() on output of strtok() -C
我是C語言的新手,我正在嘗試編寫一個程序,該程序使用兩個字符串文字,在第一個字符串中找到最長的單詞,然后將其與第二個字符串進行比較。 如果第二個字符串(稱為“期望”)的確與第一個字符串相等,則顯示成功消息,否則,將輸出實際最長的單詞,預期的字符串和原始字符串。
這里還有許多其他類似問題的帖子,但歸結為\\n
或\\0;
丟失\\0;
據我了解, strtok()
\\0
並且由於我使用的是硬編碼文字,因此我確定不會出現換行符,就像讀取輸入一樣。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char* currentTok;
static const char* result;
static char* longestTok;
static int testsExecuted = 0;
static int testsFailed = 0;
void testLongestWord();
const char* longestWord();
int totalLength();
int charLength();
int main(int argc, char *argv[]) {
printf("Testing typical cases, including punctuation\n");
testLongestWord("the quick brown foxes jumped over the lazy dogs", "jumped");
//There are other examples, some of which fail, and others don't, though I don't see a pattern
printf("\nTotal number of tests executed: %d\n",testsExecuted);
printf("Number of tests passed: %d\n",(testsExecuted - testsFailed));
printf("Number of tests failed: %d\n",testsFailed);
}
//tests words, prints success/failure message
void testLongestWord(char* line, char* expected){
result = longestWord(line, totalLength(line));
if (strncmp(result, expected,charLength(expected)-1)||totalLength(expected)==0){//the problem spot
printf("Passed: '%s' from '%s'\n",expected, line);
} else {
printf("FAILED: '%s' instead of '%s' from '%s'\n",result, expected, line);
testsFailed++;
}
testsExecuted++;
}
//finds longest word in string
const char *longestWord(char* string, int size){
char tempString[size+10];//extra room to be safe
strcpy(tempString,string);
currentTok = strtok(tempString,"=-#$?%!'' ");
longestTok = "\0";
while (currentTok != NULL){
if (charLength(currentTok)>charLength(longestTok)){
longestTok = currentTok;
}
currentTok = strtok(NULL,"=-#$?%!'' ");
}
return longestTok;
}
int totalLength(const char* string) {
int counter = 0;
while(*(string+counter)) {
counter++;
}
return counter;
}
int charLength(const char* string) {
int counter = 0;
int numChars = 0;
while(*(string+counter)) {
if (isalpha(*(string+counter))){
numChars++;
}
counter++;
}
return numChars;
}
問題是它返回:
FAILED: 'jumped' instead of 'jumped' from 'the quick brown foxes jumped over the lazy dogs'
顯然,字符串是相等的,並且我已經做了其他測試以確保它們的長度相同,具有\\0
...,但仍然失敗。
您正在調用strncmp()
,該字符串在相等的字符串上返回零,但是您正在布爾值上下文中對它進行求值,其中零為false,因此它屬於else分支。
另外,考慮使用strlen()
找出字符串的長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.