为什么我的程序在接受输入后退出?

时间:2021-07-26 09:32:03

标签: c

考虑:

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

int main() {
    int n;
    char name[100];
    int number;
    printf("Enter the value of n\n");
    scanf("%d",&n);
    printf("Enter %d values\n", n);
    for(int i=0; i<n; i++)
    {
        scanf("%[^\n]s", &name);
    }
}

每当我输入 n 的值时,它只会打印(输入 n 个值)并退出程序。 for 循环从不运行。第一次运行成功,之后就退出程序了。

有一些答案说它不会打印任何东西。我不希望它打印只是为了输入 n 次。它不是这样做的。

我的目标是将 n 作为输入,然后将名称字符串(如 harryrobin 等)作为输入 n 次。

2 个答案:

答案 0 :(得分:2)

你的代码有点不完整。这里有一些错误:scanf ("%[^\n]s", &name)

这样做,一切都会好起来的:

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

int main(void)
{
    int n;
    char name[100];
    int number;
    printf("Enter the value of n\n");
    scanf(" %d", &n);
    printf("Enter %d values\n", n);
    for(int i=0; i<n; i++)
    {
        scanf(" %99[^\n]", name);
        printf("%s\n", name);
    }
    return 0;
}

答案 1 :(得分:1)

scanf 特别不适合用户输入。

你可能想要这个:

int main() {
  int n;
  char name[100];
  int number;
  printf("Enter the value of n\n");
  scanf("%d", &n);

  printf("Enter %d values\n", n);
  for (int i = 0; i < n; i++)
  {
                                 // the space at the beginning of "%[^\n]"
                                 // gets rid of the \n which stays in the input buffer
    scanf(" %[^\n]", name);      // also there sis no 's' at the end of the "%[^\n]" specifier 
    printf("name = %s\n", name); // for testing purposes
  }
}

但这实际上没有多大意义,因为程序要求输入 n 个名称,但是在 for 循环的每次运行中,以前的名称将被新名称覆盖。

另请注意,scanf("%[^\n]", name); 是有问题的,因为如果用户键入的字符超过 99 个,您将导致缓冲区溢出。