C 程序 Do while 不起作用

标签 c do-while

我的程序有问题。我不知道我做错了什么,但循环 do while 不起作用。程序应询问“如果您想再次运行此程序,请按 T。其他键应关闭此程序。

#include "stdafx.h"
#include <stdlib.h>
#include <conio.h>
#include <time.h>

int main()
{
int a;
int b;
int c;
int f;
int g;
int h;
int d = 0;
char e;
srand(time(0));
do {

    printf("How many numbers do you want to show: ");
    scanf_s("%i", &a);
    printf("od: ");
    scanf_s("%i", &b);
    printf("do: ");
    scanf_s("%i", &c);

    h = c + 1;
    f = b - h; 
    for (d; d < a; d++) {
        printf("%i ", b + rand() % f);
    }
    printf("\n");
    printf("Restart program? T- Yes");
    scanf_s("%s", &e);

} while (e == 't');

_getch();
return 0;
}

程序工作正常,但是当我最后按 T 时。它会关闭。我使用的是 Visual Studio 2015

现在我的代码如下:

do {

    printf("How many numbers do u want: ");
    scanf_s("%i", &a);
    printf("od: ");
    scanf_s("%i", &b);
    printf("do: ");
    scanf_s("%i", &c);

    h = c + 1; 
    f = b - h; 
    //printf("%i %i %i\n", h, f);
    for (d; d < a; d++) {
        printf("%i ", b + rand() % f);
    }
    printf("\n");
    printf("Restart? T- yes");
    scanf_s("%c", &e);
} while (e == 't' || e == 'T');
_getch();
return 0;
}

但是还是不行。我无法输入任何字母。当我按任意键时,窗口将关闭

最佳答案

正如其他人所指出的,这是因为您正在尝试获取 "%s",因此无法将其与字符进行比较。请使用 "%c" 代替,或使用 strcmp 函数来比较 2 个字符数组。

顺便说一句,请注意 scanf_s 是 Microsoft 独有的函数。不确定 Visual Studio 是否强制您使用它,但 scanf 的常见用法不会有什么坏处,请检查一下:

scanf("%c", &e);

关于C 程序 Do while 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46891858/

相关文章:

java - (添加)圈与叉游戏。 While 循环

java - 在java中使用while循环进行字符检查(BufferedReader)

java - Do while 循环比较字符串

c - 是否可以在 C 中使 union 右对齐?

c - GCC 缺少带有静态模块级变量的初始化程序周围的大括号

c - 如何修复 "HDF5-DIAG: Error unable to open file"?

java - 作为 Java 开发人员,C 还是 C++?

Python 3 兼容性问题

javascript - 使 continue 语句在 do while 循环中工作

java - 将 while 循环嵌套在 do while 循环内