gets(name) 不起作用;在 Turbo C++ 中

问题描述 投票:0回答:1

`你能帮我吗,代码看起来像这样 基本:

#include<stdio.h>
int main()
{
char name[100];
int age;

clrscr();

printf("Enter Your Name: \n");
gets(name);
printf("Enter Your Age: ");
if(scanf("%d", &age)!=1)
{
goto basic;
}
return 0;
}

这段代码基本上如果你在年龄中输入任何非整数值,它就会返回。但是当它返回时 printf 输入的你的名字不能被修改

如果我去 main(); 有什么办法吗?或者转到基本我将能够输入一些内容来输入您的名字?`

turbo-c++
1个回答
0
投票
  1. 您可以使用
    while
    do-while
    循环重复询问姓名和年龄,直到提供有效的输入。
#include <stdio.h>

int main() {
    char name[100];
    int age;
    int status;

    do {
        printf("Enter Your Name: \n");
        fgets(name, 100, stdin); // Using fgets instead of gets for safety

        printf("Enter Your Age: ");
        status = scanf("%d", &age);

        while (getchar() != '\n'); // Clear the input buffer

    } while(status != 1); // Repeat if age input is invalid

    return 0;
}

在此版本中,

do-while
循环将继续询问姓名和年龄,直到输入有效的年龄整数。请注意,使用
fgets
代替
gets
,因为
gets
不安全且已弃用。

  1. 虽然由于可读性和可维护性问题通常不建议这样做,但您也可以使用
    goto
    跳回到输入过程的开始位置。
© www.soinside.com 2019 - 2024. All rights reserved.