简单的字符串递归

时间:2013-04-14 19:06:15

标签: c string loops recursion logic

我正在尝试使用字符串,我遇到了一个无法调试的问题。

此脚本的目标是对一个字符串运行5次测试,检测每个字符串的字符串长度,同时为字符串提供参数(输入的最小字符数和最大值) 有问题的字符串是 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
}

它可以100%正常工作,如果你没有超过Max或Min设置。该程序会阻止你并要求你重新输入你的字符串(如果你这样做)但是某些东西会继续存在。

  • 例如,如果您将“结束”写为字符串,则会询问您 重新说,因为它只有3个字符。
  • 如果您将下一个字符写为“结束”,它将为您提供3个字符(这是 不正确,应该是7个字符;包括空间。)
  • 再次编写“结束”将为您提供正确数量的字符。
  • 经过测试,看它是否真的在阅读您之前写的“ The End ”,但事实并非如此。所以我必须假设问题将在递归上的某些逻辑循环监督中。

感觉就像程序在递归中的 if语句(这就是我可以缩小问题的范围),我无法理解我的生活为什么@ __ @到目前为止,我已尝试使用

清除字符串
str[0]='\0';

几乎到处都是铺板,但无济于事:( 非常感谢帮助!学习很有趣,但是当你无法找到真正出错的线索时会感到沮丧。

感谢您阅读!


修改: 在str[i+1]='\0';下移动i++;,这将在字符串前面为每次尝试设置空值。事实证明,它会为工作字符串和非工作字符串设置一个空值,因为它被置于一个坏点。感谢 Dave

如果您有一些有趣的见解或其他答案,我肯定会读到它! :)

1 个答案:

答案 0 :(得分:1)

在递归后你需要return

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