繁体   English   中英

简单的字符串递归

[英]Simple String Recursion

我正在尝试使用字符串进行调试,但是遇到了无法调试的问题。

该脚本的目标是对一个字符串进行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%正常工作。 该程序将阻止您,并要求您重新输入字符串(如果这样做)(应该这样做),但是有些东西会保留下来。

  • 例如,如果您将“ End ”写为字符串,它将要求您重新输入,因为它只有3个字符。
  • 如果将下一个字符写为“ The End ”,它将给您3个字符(不正确,应为7个字符;包括空格。)
  • 再次写“ The End ”将为您提供正确的字符数。
  • 测试了一下是否真的在阅读您之前编写的“ The End ”,但事实并非如此。 因此,我必须假设问题将在递归的某些逻辑循环监督中进行。

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

str[0]='\0';

而且实际上到处都是木板,但无济于事:(真的很感谢您的帮助!学习很有趣,但是当您没有任何办法了解真正出了什么问题时,便会感到沮丧。

感谢您的阅读!


编辑 :移动str[i+1]='\\0'; i++; 每次尝试都会在字符串前设置一个空值。 原来的问题是,由于它放置在坏处,因此它将为工作和不工作的字符串设置一个空值。 谢谢戴夫

如果您有一些有趣的见解或需要补充的其他答案,我一定会读的! :)

您需要在执行递归后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);
    }   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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