简体   繁体   中英

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.

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.

If i put cad_look_str(s1,s1) on the last line, it works fine... Why is this happening?

Regards

Your initial loop condition will never terminate if the first characters don't match your comparison test within your if statement.

The 'while' loop checks to ensure the current character positions (both 0 on first pass) are non-terminators. If they're not, and they're not equal, indS1 is reset to its starting position. indS2 never changes, thus the while condition is unchanged.

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.

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

changed cad_look_str() for situations like s1 : gdgddadada, s2 : dadada

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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