0
我試圖從文本文檔中搜索關鍵詞我試圖排除空格,新行和製表符。我能夠從文件中讀取輸入,但無法讓我的strcmp和計數器發生變化。我試圖使用printf語句來找出問題,但我仍然迷失。如果它的語法問題讓我知道。任何幫助,將不勝感激。在C中使用Strcmp
if(p = 0)
它應該是::
繼承人的代碼
FILE *file2 = fopen(argv[2], "r");
if (file2 == NULL) {
printf("\nFile 2 could not open\n");
} else {
do {
// treat all new line as spaces.
x = fgetc(file2);
if (x == '\n') {
x = 32;
}
if (x == '\t') {
x = 32;
}
if(x != 32) {
temp[l] = x;
} else {
temp[l] == '\0';
printf("\t%s", temp);
for(a=0; a < countw; a++) {
p = strcmp(swords[a].word,temp);
if (p = 0) {
swords[a].count++;
}
printf("\nstop%i\n",a);
}
for(b=0; b<l; b++) {
temp[b] = '\0';
}
l = 0;
}
} while (x != EOF);
}
fclose(file2);
避免意外分配常量的另一個好方法是顛倒順序。 'if(0 == p)'在邏輯上是相同的,但是如果你省略了一個'=',那麼它將不能編譯。或者,在這種情況下,你不需要'p',只需要寫'if(strcmp(sword [a] .word,temp)== 0)' –
@ChrisRyding:關於[Yoda條件]( http://en.wikipedia.org/wiki/Yoda_conditions)是避免這種錯誤的一種很好的方法。就我個人而言,我發現'如果(0 == p)'刺耳和違反直覺。 –
我已經嘗試了這兩種方法,既不會導致計數器增量。也許它是因爲我正在使用一個結構? – user3549899