gpt4 book ai didi

c - 简单的字符串递归

转载 作者:行者123 更新时间:2023-11-30 15:49:59 24 4
gpt4 key购买 nike

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

此脚本的目标是对一个字符串运行 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++; 下,每次尝试都会在字符串前面设置一个空值。事实证明,问题在于它会为工作和不工作的字符串设置一个空值,因为它被放置在一个坏的地方。感谢戴夫为此!

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

最佳答案

执行递归后需要返回:

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

关于c - 简单的字符串递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16003127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com