c语言 - 用不同的编程结构替换"goto"



我正在尝试使用防御性编程来做这个小程序,但是我很难处理这个问题,避免使用Loop-Goto,因为我知道这是糟糕的编程。我试过一段时间,做...虽然循环,但在一种情况下我没有问题。当我要做另一个时,问题就开始了...而对于第二种情况("不插入空格或单击输入按钮")。我尝试并嵌套做...而在这里,结果更加复杂。

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i;
int length;
char giventext [25];        
Loop:
printf("String must have 25 chars lenght:n");
gets(giventext);
length = strlen(giventext);
if (length > 25) {
printf("nString has over %d chars.nMust give a shorter stringn", length);
goto Loop;
}
/* Here i trying to not give space or nothing*/
if (length < 1) {
printf("You dont give anything as a string.n");
goto Loop;
} else {
printf("Your string has %dn",length);
printf("Letter in lower case are: n");
for (i = 0; i < length; i++) {
if (islower(giventext[i])) {                            
printf("%c",giventext[i]);
}
}
}
return 0;
}

请注意,您的代码根本不具有防御性。您无法避免缓冲区溢出,因为,

  1. 在字符串输入到程序后检查字符串的长度,以便在缓冲区溢出已经发生之后,并且
  2. 您使用gets()它不检查输入长度,因此很容易出现缓冲区溢出。

请改用fgets(),只丢弃多余的字符。

我认为您需要了解strlen()不计算输入的字符数,而是计算字符串中的字符数。

如果要确保插入的字符少于N个,则

int
readinput(char *const buffer, int maxlen)
{
int count;
int next;
fputc('>', stdout);
fputc(' ', stdout);
count = 0;
while ((next = fgetc(stdin)) && (next != EOF) && (next != 'n')) {
// We need space for the terminating '';
if (count == maxlen - 1) {
// Discard extra characters before returning
// read until EOF or 'n' is found
while ((next = fgetc(stdin)) && (next != EOF) && (next != 'n'))
;
return -1;
}
buffer[count++] = next;
}
buffer[count] = '';
return count;
}
int
main(void)
{
char string[8];
int result;
while ((result = readinput(string, (int) sizeof(string))) == -1) {
fprintf(stderr, "you cannot input more than `%d' charactersn", 
(int) sizeof(string) - 1);
}
fprintf(stdout, "accepted `%s' (%d)n", string, result);
}

请注意,通过使用函数,该程序的流量控制清晰简单。這正是為什麼goto不氣馁,不是因為它是一件邪惡的事情,而是因為它可以像你一樣被濫用。

尝试使用标记程序需要执行的逻辑步骤的函数:

char * user_input()- 返回来自用户的输入作为指向字符的指针(使用get()以外的其他内容!例如,查看scanf)

bool validate_input(char * str_input)- 从上述函数获取用户输入并执行检查,例如验证长度是否在 1 到 25 个字符之间。

str_to_lower(char * str_input)- 如果validate_input()返回 true,则可以调用此函数并向其传递用户输入。然后,此函数的主体可以小写将用户输入打印回控制台。您可以使用此处tolower()的标准库函数将每个字符小写。

然后,主函数的主体将简单得多,并执行一系列逻辑步骤来解决您的问题。这是防御性编程的本质 - 将您的问题模块化为独立的且易于测试的单独步骤。

主函数的可能结构可以是:

char * user_input();
bool validate_input(char *);
void str_to_lower(char *);
int main()
{
char * str_input = user_input();
//continue to get input from the user until it satisfies the requirements of 'validate_input()'
while(!validate_input(str_input)) { 
str_input = user_input();
}
//user input now satisfied 'validate_input' so lower case and print it
str_to_lower(str_input);
return 0;
}

最新更新