简体   繁体   English

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

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

i'm making a small test to see if a word is inside another, and i want to return the index where that word begins. 我正在做一个小测试,看看一个单词是否在另一个单词中,我想返回该单词开头的索引。

Example: if i check "um" inside "amolum" the return value should be 4(position of the leter "u" where the word begins. 示例:如果我在“amolum”中检查“um”,则返回值应为4(单词开头的字母“u”的位置)。

This is what my code looks like: 这就是我的代码:

(...)
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) );
}

The problem is that when i compile this, it doesn't stop looping on scanf... It just continues to ask for strings. 问题是当我编译它时,它不会停止在scanf上循环...它只是继续要求字符串。

If i put cad_look_str(s1,s1) on the last line, it works fine... Why is this happening? 如果我把cad_look_str(s1,s1)放在最后一行,它可以正常工作......为什么会这样?

Regards 问候

Your initial loop condition will never terminate if the first characters don't match your comparison test within your if statement. 如果第一个字符与if语句中的比较测试不匹配,则初始循环条件将永远不会终止。

The 'while' loop checks to ensure the current character positions (both 0 on first pass) are non-terminators. 'while'循环检查以确保当前字符位置(第一次传递时均为0)是非终止符。 If they're not, and they're not equal, indS1 is reset to its starting position. 如果它们不相同,并且它们不相等, indS1重置为其起始位置。 indS2 never changes, thus the while condition is unchanged. indS2永远不会改变,因此while条件不变。

Might look at some other string functions to accomplish your task unless the scanning is a mandatory component for some reason. 除非由于某种原因扫描是必需组件,否则可能会查看其他一些字符串函数来完成您的任务。

Index of second string should be incremented in the else part also. 第二个字符串的索引也应该在else部分递增。

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

changed cad_look_str() for situations like s1 : gdgddadada, s2 : dadada 为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