[英]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%正常工作。 该程序将阻止您,并要求您重新输入字符串(如果这样做)(应该这样做),但是有些东西会保留下来。
感觉好像程序正在递归中的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.