1
#include <stdio.h>

int stringLength (char *text)
{
  int count = 0;
  while (*text != '\0')
  {
    count++;
    text++;
  }


  return count;
}


int main()
{
  char str[25];
  int length;

  printf("ENter string: ");
  scanf("%s", &str);

  length = stringLength(str);
  if (length > 25)
  {
    printf("Invalid\n");
    printf("Enter string: ");
    scanf("%s", &str);
  }
  printf("Your string is: %s and its %d long", str, length);
  return 0;
}

If the first input is wrong (over 25) it will remember that number (length) and when I input another string it will add the numbers together. How do I fix it so it goes from beginning? So it counts the next string from start?

Baja
  • 55
  • 1
  • 1
  • 4
  • is `stringLength` called on new string? – Alexander Dmitriev Nov 25 '20 at 20:55
  • 2
    With `scanf("%24s", str);` you can make sure that at most 24 chars (one has to be left for the terminator) are stored – Roberto Caboni Nov 25 '20 at 20:56
  • 2
    If the length of the string is more than ***24***, there will not be enough room to store it and the terminating null byte inside `char str[25]`. If that happens, you will cause undefined behaviour, probably trashing data on the stack such as the `length` variable and/or your `main()` function's return address. Change `scanf("%s", &str);` to `scanf("%24s", &str);` to avoid this. Checking for a buffer overflow after the fact is not a reliable solution. – r3mainer Nov 25 '20 at 20:56

2 Answers2

2

You can't in this way. Your code has at least two problems:

  1. You don't have to use the & when you pass a string to scanf, because str is already a pointer (search the equivalence pointer and array in C).
  2. If you insert more than 25 what is happening is a buffer overflow and your program presents an undefined behavior after the scanf. You may want to consider a different and safer approach to read from keyboard (e.g. fgets)
ocirocir
  • 3,543
  • 2
  • 24
  • 34
1
 char str[25];

Can only contain a string of 24 char + NULL. Use a width specifier to limit input to 1 less than buffer size when scanning strings into scanf().

Replace the if() branch with a while() loop:

length = stringLength(str);
  while(length > 24)// an array of 25 elements can only accommodate 24 characters + NULL 
  {
    printf("Invalid\n");
    printf("Enter string: ");
    //use input limiter of 24 for char str[25];
    scanf("%24s", str);//remove & (for all scanf scanning a string)
    length = stringLength(str);
  }
ryyker
  • 22,849
  • 3
  • 43
  • 87