【发布时间】:2024-01-17 19:35:01
【问题描述】:
我刚开始学习编程,我正在玩指针和 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
我试图了解为什么会发生这种情况,但我找不到答案。
谢谢!
【问题讨论】:
-
您没有正确复制代码,打印位数的行缺少结尾。
-
%s格式用于读取字符串,但x是单个字符。