首页 > 解决方案 > 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

我试图理解为什么会发生这种情况,但我找不到答案。

谢谢!

标签: cfor-loopscanf

解决方案


第一,你没有声明一个字符串,你声明了一个字符并将其视为一个字符串,这会给你带来各种各样的麻烦。可能是为什么你会得到奇怪的值。char x应该是char x[16]数字的最大长度(以数字为单位)加一,因为字符串在 C 中以空字符 (0) 结尾。当您引用此字符串时,因为它是一个字符数组,所以您不要t 需要地址操作符&(除非你想要一个指向字符串的指针而不是字符串本身,比如如果你将它作为函数的输出传递)。printf("%c", *(&x + i))更好更清楚地写成printf("%c",x[i])甚至putchar(x[i])

scanf不适用于用户输入。最好fgets用于此目的。这也更安全,因为fgets需要最大长度。用于论证stdinFILE一定要检查返回值;这将NULL是没有更多数据时的值。通常这是当您Control-D在 Unix 中按下键或Control-Z在 Windows 中按下键时。


推荐阅读