【问题标题】:For loop not stopping or updating initial valueFor循环不停止或更新初始值
【发布时间】: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 是单个字符。

标签: c for-loop scanf


【解决方案1】:

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

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

【讨论】:

  • 谢谢@eewanco,这真的很有帮助。非常感谢。
  • 另外,为什么 scanf 对用户输入不可靠,我看到的每个地方都说这对它不利?
  • 但是为什么不打印#number?为什么当我按Enter时它会无限循环?因为#number 的值在#2 处停止并重复?,是不是因为一遍又一遍地读取同一个内存地址?
  • 所有的赌注都失败了,因为您通过仅定义一个 char 并像字符串一样使用它来覆盖内存。先解决你的字符串问题,如果它仍然发生,我们会看看它。