c - For循环不停止或更新初始值
问题描述
我刚开始学习编程,我正在玩指针和 scanf。我正在尝试制作一个程序,询问用户 n (代码中的案例),然后提示用户输入 n 次数字,但是一旦我在终端中,它就不会停止。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int cases;
//prompt the user for number of cases
printf("cases:\n");
scanf("%d",&cases);
// will print the number of digits of the users number
for (int j = 0; j < cases; j++)
{
printf ("#%i:\n",j + 1);
char x;
int size;
scanf(" %s",&x);
size = strlen(&x);
//use printf to see what the program is doing
printf("the number of cases are:%d",cases);
printf("the current case is:%d\n",j + 1);
printf("the number of digits are:%i\n",si
}
//print back the users input
for (int i = 0; i < size; i++)
{
printf("%c", *(&x + i));
}
printf("\n");
}
编译并尝试按回车后“#number”没有被更新,这就是出现的内容:
cases:
3
#1:
564
the number of cases are:3
the current case is:13367
the number of digits are:3
或者也
cases:
5
#1:
3
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
4
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
6
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
7
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
7
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
8
the number of cases are:5
the current case is:1
the number of digits are:1
我试图理解为什么会发生这种情况,但我找不到答案。
谢谢!
解决方案
第一,你没有声明一个字符串,你声明了一个字符并将其视为一个字符串,这会给你带来各种各样的麻烦。可能是为什么你会得到奇怪的值。char x
应该是char x[16]
数字的最大长度(以数字为单位)加一,因为字符串在 C 中以空字符 (0) 结尾。当您引用此字符串时,因为它是一个字符数组,所以您不要t 需要地址操作符&
(除非你想要一个指向字符串的指针而不是字符串本身,比如如果你将它作为函数的输出传递)。printf("%c", *(&x + i))
更好更清楚地写成printf("%c",x[i])
甚至putchar(x[i])
。
scanf
不适用于用户输入。最好fgets
用于此目的。这也更安全,因为fgets
需要最大长度。用于论证stdin
。FILE
一定要检查返回值;这将NULL
是没有更多数据时的值。通常这是当您Control-D
在 Unix 中按下键或Control-Z
在 Windows 中按下键时。
推荐阅读
- python - 如何使用 if 条件在 1D 和 2D numpy 数组之间进行矢量化计算
- c++ - 检查文件描述符中可用缓冲区字符的数量
- javascript - 未捕获的类型错误:无法读取 HTMLImageElement 处未定义的属性“切换”。
- python-3.x - 如何在 Amazon Linux 环境中安装 Python mariadb 模块
- json - 将 JSON 转换为 multipart/form-data angular/ionic
- html - 为什么父母的孩子复制父母的背景图片?
- node.js - 我不知道如何部署这个
- excel - 仅获取特定范围的一个原始结果
- python - 如何导入 Pandas 分析
- php - Woocommerce 免费送货最低金额与货币转换