c - C程序运行时错误

标签 c

以下代码给出运行时错误,我只是找不到代码中的问题。那么是否有人可以提供帮助?

#include<stdio.h>
int main() {
    int a = 0;
    while(1){
        scanf("%d",&a);
        if(a==42)
            break;  
        printf("%d\n",a);

    }
    return 0;
}

最佳答案

如果您想扫描用户输入直到按下有效输入,您可以使用以下代码:

#include <stdio.h>

int main() {
    char a = 0;
    while(1){
        scanf("%c",&a);
        if(a==42)
            break;  
        printf("%d\n",a);
    }
    return 0;
}

此代码不会卡在任何输入上,但它会逐个字符地处理输入,因此您可能会因为输入而在控制台上看到类似 10 的内容。要结束此程序,如果我们有 ascii 编码,则有效的用户输入是 *

正如您在 scanf man page 中看到的那样:

On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.

它将返回成功匹配输入的数量,以便您可以检查该值以确保您的代码在输入缓冲区上取得进展。

关于c - C程序运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44487729/

相关文章:

c# - 需要一些帮助将此 C 代码移植到 C#

c - 无法从客户端连接到套接字

c - OpenGL 应用程序中不显示三角形

c - 奇数 'skip' 函数 : error when running is double loops

c - 二维数组的 malloc

c - int 产生接近正确的答案,但 float 只给出 -18.000

c - .obj 文件是否包含二进制语言的机器代码?

c - 为什么 -Werror 导致配置错误

c - 当 ICANON 处于非规范模式时如何避免退格

c - Sleep() 不准确吗?