【问题标题】:Simple String Recursion简单的字符串递归
【发布时间】:2023-03-08 13:56:01
【问题描述】:

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

此脚本的目标是对一个字符串运行 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 设置。程序会阻止你并要求你重新输入你的字符串,如果你这样做(应该)但是有 something 可以继续。

  • 例如,如果你写“End”作为字符串,它会要求你 重新输入,因为它只有 3 个字符。
  • 如果您将下一个字符写为“The End”,它将为您提供 3 个字符(即 不正确,应该是7个字符;包括空间。)
  • 现在再次编写“The End”将为您提供正确数量的字符。
  • 测试看看它是否真的在阅读你之前写的“The End”,但不是。所以我必须假设问题出在对递归的一些逻辑循环监督中。

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

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

几乎到处都铺板,但无济于事:( 非常感谢帮助!学习起来很有趣,但是当您无法了解到底出了什么问题时会感到沮丧。

感谢您的阅读!


编辑: 将str[i+1]='\0'; 移动到i++; 下,这将为每次尝试在字符串前面设置一个空值。原来问题在于它会为工作和不工作的字符串设置一个空值,因为它被放置在一个不好的位置。感谢戴夫

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

【问题讨论】:

  • 实际上,当您检查String_Insert_Recursion 中的字符串长度时,您可能已经覆盖了数组的末尾。
  • 你的问题是递归而不是直接的字符串。只需使用一个循环。 (具体来说,str[i+1]='\0'; 正在为成功的字符串 之前的不成功字符串运行)
  • 没看到!好消息:) 把它卡在 i++ 下,到目前为止它工作得很好,我会对其进行压力测试,看看我是否可以把它搞砸,或者它是否被永久修复。啊啊啊,谢谢戴夫。我必须确保我以后不会犯这样的错误!

标签: c string loops recursion logic


【解决方案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);
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2017-10-28
    • 1970-01-01
    • 2020-03-10
    • 2016-06-25
    • 1970-01-01
    • 2023-01-11
    相关资源
    最近更新 更多