简体   繁体   English

strcmp不工作,所以即使strcmp中的两个字符串变得相等,程序也不会超出for循环

[英]strcmp not working and the so the program is not breaking out of the for loop even if there is a point where the two strings in strcmp become equal

Though word and s2 are same the if(strcmp) statement is not executed. 虽然word和s2相同,但是不执行if(strcmp)语句。 Where is the mistake?? 这个错误在哪里? I checked the code for reading from a file and tried out "printf" to see whether word and s2 are the same or not and found that they become same after about 10 iterations and should break out at that point but the program executes till i is less than zero. 我检查了从文件中读取的代码并尝试了“printf”以查看word和s2是否相同,并发现它们在大约10次迭代后变得相同并且应该在那时突破但是程序执行直到我是小于零。

Please help. 请帮忙。 Thanks in advance. 提前致谢。 PS "words.txt" is the inbuilt dictionary file in the fedora operating system PS“words.txt”是fedora操作系统中的内置字典文件

#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
     FILE *ptr;
     ptr=fopen("./words.txt","r");
     char word[40];
     char ch;
     int i=70,j=0;
     char s2[] = "2";
     while(i>0){
          while (ch!='\n') {
               ch=fgetc(ptr);
               word[j]=ch;
               j++;
          } 
          word[j]='\0';
          if(strcmp(s2,word) == 0){
             break;
          }
          j=0; 
          if(ch=='\n'){
              ch=fgetc(ptr);
              word[j]=ch;
              j++;        
          }
          i--;
     }
     fclose(ptr); 
     return 0;
 }

You are using a variable before initializing its value: 您在初始化其值之前使用变量:

while (ch != '\n') {

Anything could happen since the initial value of ch is not known. 由于ch的初始值未知,因此可能发生任何事情。 However, the odds are high (255 out of 256 chances) that the expression is initially true. 但是,表达式最初为真的几率很高(256个机会中有255个)。 After it has entered the loop once, all is well. 进入循环一次后,一切都很顺利。

For the loop to work as expected, do not store \\n in the buffer. 要使循环按预期工作,请不要将\\n存储在缓冲区中。 Since s2 does not contain \\n , strcmp() will never match as long the the newline is stored in there. 由于s2不包含\\n ,因此只要新行存储在那里, strcmp()就永远不会匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM