Pedro Lino
Pedro Lino

Reputation: 601

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

Upvotes: 3

Views: 672

Answers (3)

user207064
user207064

Reputation: 665

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

Upvotes: 1

user207064
user207064

Reputation: 665

Index of second string should be incremented in the else part also.

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

Upvotes: 2

David W
David W

Reputation: 10184

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.

Upvotes: 2

Related Questions