我正在尝试使用字符串,我遇到了一个无法调试的问题。
此脚本的目标是对一个字符串运行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设置。该程序会阻止你并要求你重新输入你的字符串(如果你这样做)但是某些东西会继续存在。
感觉就像程序在递归中的 if语句(这就是我可以缩小问题的范围),我无法理解我的生活为什么@ __ @到目前为止,我已尝试使用
清除字符串str[0]='\0';
几乎到处都是铺板,但无济于事:( 非常感谢帮助!学习很有趣,但是当你无法找到真正出错的线索时会感到沮丧。
感谢您阅读!
修改:
在str[i+1]='\0';
下移动i++;
,这将在字符串前面为每次尝试设置空值。事实证明,它会为工作字符串和非工作字符串设置一个空值,因为它被置于一个坏点。感谢 Dave !
如果您有一些有趣的见解或其他答案,我肯定会读到它! :)
答案 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);
}
}