繁体   English   中英

C - scanf不会停止字符串输入中的循环

[英]C - scanf doesn't stop looping in string input

我正在做一个小测试,看看一个单词是否在另一个单词中,我想返回该单词开头的索引。

示例:如果我在“amolum”中检查“um”,则返回值应为4(单词开头的字母“u”的位置)。

这就是我的代码:

(...)
int cad_look_str (char s1[], char s2[]) {
  int indS1 = 0, indS2 = 0;

  while (s1[indS1]!='\0'|| s2[indS2]!='\0') {
    if (s1[indS1]==s2[indS2]) {
      indS1++;
      indS2++;
    }
    else indS1=0;
  }

  if (s2[indS2]=='\0' && s1[indS1]!='\0') return -1;
  else return indS2-strlen (s1);
}


void main () {
  char s[100];
  char s1[100];

  scanf ("%s",s); 
  scanf ("%s",s1);

  printf ("%d \n", cad_look_str(s1,s) );
}

问题是当我编译它时,它不会停止在scanf上循环...它只是继续要求字符串。

如果我把cad_look_str(s1,s1)放在最后一行,它可以正常工作......为什么会这样?

问候

如果第一个字符与if语句中的比较测试不匹配,则初始循环条件将永远不会终止。

'while'循环检查以确保当前字符位置(第一次传递时均为0)是非终止符。 如果它们不相同,并且它们不相等, indS1重置为其起始位置。 indS2永远不会改变,因此while条件不变。

除非由于某种原因扫描是必需组件,否则可能会查看其他一些字符串函数来完成您的任务。

第二个字符串的索引也应该在else部分递增。

if (s1[indS1]==s2[indS2])
{
        indS1++; indS2++;
}
else {
         indS1=0;
         indS2++;
}

为s1:gdgddadada,s2:dadada等情况更改了cad_look_str()

int cad_look_str (char s1[], char s2[]) {
  int indS1 = 0, indS2 = 0;
  int flag = 0;


  while (s1[indS1]!='\0'&& s2[indS2]!='\0') {
    if (s1[indS1]==s2[indS2]) {
      indS1++;
      indS2++;
      flag = 1;
    }
    else 
    {
        indS1=0;
        indS2++;
        if(flag) indS2--; // to work with srtrings s1: gdgddadada s2: dadada
        flag = 0;
    }
  }

  if (s2[indS2]=='\0' && s1[indS1]!='\0') return -1;
  else return indS2-strlen (s1);
}

暂无
暂无

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

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