Farstride
Farstride

Reputation: 145

Simple String Recursion

I'm trying my hand out with strings, and I've run into a problem I can't debug.

The goal of this script is to run 5 tests on one string, detecting the string length of each string, while giving the string a parameter (Minimum characters to input, and max) string in question is str[]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 11
#define MIN_SIZE 5

void String_Insert_Recursion(char str[]);

int main(int argc, char *argv[])
{
   char str[SIZE];
   int i, str_lenght;

   printf("Enter a string of %i to %i characters:\n", MIN_SIZE, SIZE-1);
   for (i=0; i<5 ; i++)
   {
      String_Insert_Recursion(str);  
      str_lenght = strlen(str);
      printf("This string is %i long\n", str_lenght-1);
   }


   system("PAUSE"); 
   return 0;
}


 void String_Insert_Recursion(char str[])
{
   int i=0;
   while ((str[i] = getchar()) != '\n')
      i++;

   if (i>SIZE-1 || i<MIN_SIZE)
      {
      //SIZE-1 so that there's still ONE spot on the string for a null value.
      printf("Incorrect number of characters. Please Reenter\n");
      String_Insert_Recursion(str);
      }

   str[i+1]='\0';
   //This sets the null value at the end of the string
}

It works 100% fine, if you don't go over the Max or Min setup. The program will stop you and ask you to re-input your string if you do (As it should) but there's something that carries over.

It feels like the program is mucking up at the if statement in the recursion (That's as far as I could narrow down the problem), I can't understand for the life in me why @__@ So far, I've tried clearing the string out using

str[0]='\0';

And planking that practically everywhere, to no avail however :( Would really appreciate help! It's interesting to learn, but frustrating when you don't have any way to get a clue on what's really going wrong.

Thank you for reading!


EDIT: Moved str[i+1]='\0'; under the i++; which will set a null value ahead of the string for every attempt. Turns out the problem was that it would set a null value to both working and unworking strings since it was placed in a bad spot. Thank you to Dave for this!

If you've got some interesting insight or another answer to add, I will definitely read it however! :)

Upvotes: 0

Views: 130

Answers (1)

perreal
perreal

Reputation: 97938

You need to return after doing the recursion:

void String_Insert_Recursion(char str[])
{
    int i=0;
    while ((str[i] = getchar()) != '\n')
        i++;
    if (i < SIZE && i>=MIN_SIZE) {
        str[i+1]='\0';
    } else {
        printf("Incorrect number of characters. Please Reenter\n");
        String_Insert_Recursion(str);
    }   
}

Upvotes: 1

Related Questions