c - 程序未完全执行并跳过语句

标签 c

我用 C 语言编写了一个简单的程序,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int length;
printf("Enter the length of the string:\t");
scanf("%d",&length);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}

当我执行它时 - 我得到的输出为:

Enter the length of the string: 5
Enter string:
Process returned 0 (0x0)   execution time : 1.740 s
Press any key to continue.

我不知道为什么它不要求输入字符串并直接退出程序。

最佳答案

当您输入“5”并按回车键时,您将向程序发送两个字符 -“5”和换行符。因此,您的第一个 scanf 获取“5”,第二个获取换行符,并将其转换为数字零。

参见How to read a line from the console in C?

关于c - 程序未完全执行并跳过语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207076/

相关文章:

c - 如何根据 IEEE 754 (ansi-c) 获取 double 的上/下机器字?

c - 我应该如何打印像 off_t 和 size_t 这样的类型?

c - d2i_RSA_PUBKEY 总是返回 NULL

计算C中文本文件每行的字符数

c - 按值和指针传递

c - C中的猜谜游戏,无法获得有效的尝试次数,变量为 "counter"

c - ANTLR C目标和XMLLib

将字符串转换为名称标识符

c - write函数在Unix上需要unistd.h,windows呢?

c - 获取指向 4 维数组中子数组的指针