0

我有一个程序可以接收用户输入的课堂和时间。课堂输入存储在 char* 课堂中,时间存储在 int 时间中。但是,当我运行该程序时,它会在我键入教室后按 Enter 时停止。“请输入时间:”的 printf 没有出现。为什么会这样??

void option1()
{
  char* classroom; 
  int time;        

  printf("Please enter the classroom: ");
  scanf_s("%s", &classroom); 

  printf("Please enter the time: ");
  scanf_s("%d", &time);
}

感谢帮助 :)

4

4 回答 4

2

正如我已经评论过的,这个片段中有很多错误:

  • scanf_s绝不与 相同scanf,它需要额外的尺寸参数。我建议不要使用它。
  • 切勿仅使用"%s"with scanf(),您需要指定字段宽度以防止缓冲区溢出。(这是不同的,scanf_s()因为缓冲区大小是那里的一个附加参数。)
  • 您尝试通过不指向classroom任何地方的指针()写入数据,您需要分配内存!(通过将其设为数组或调用malloc())。

纠正了这些错误的代码段可能如下所示:

void option1()
{
  char classroom[128];
  int time;        

  printf("Please enter the classroom: ");
  scanf("%127s", classroom);
  // field width is one less than your buffer size,
  // because there will be a 0 byte appended that terminates the string!

  printf("Please enter the time: ");
  scanf("%d", &time);
}
于 2017-07-27T11:11:41.553 回答
0

使用scanf代替scanf_s,为 char 指针分配内存并且不要使用&,它已经是一个指针。请参见下面的示例:

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

int main()
{
  int time;        
  char* classroom; 
  classroom = malloc(sizeof(char) * 1024);

  if(classroom == NULL)
  {
    fprintf(stderr, "Failed to allocate memory!\n");
    exit(1);
  }

  printf("Please enter the classroom: ");
  scanf("%s", classroom); 

  printf("Please enter the time: ");
  scanf("%d", &time);


  printf("\nClassroom: %s\n", classroom);
  printf("Time: %d\n", time);

  free(classroom); //Free the memory

  return 0;
}
于 2017-07-27T11:12:31.113 回答
0

scanf系列函数将格式字符串指定的数据读取到作为参数提供的变量中。

这些函数为字符串变量分配存储空间!在没有为其分配内存的情况下向 scanf提供变量classroom,将使 scanf 尝试将数据放置在内存中未定义的位置。这可能导致任何类型的行为,通常称为未定义行为

因此,您必须首先为您的字符串变量分配存储空间,例如:

char*classroom= malloc(1024);

现在您可以使用它调用 scanf :

scanf_s("%s", classroom);

请注意,因为 char 指针表现为一个数组(即它指向一个 char 数组),所以不要使用运算符的地址&.

于 2017-07-27T11:13:20.617 回答
0

要么将变量创建为指针并为其分配内存,要么分配 char 数组并将其传递给 scanf。

//Use of array
char classroom[10];
scanf("%9s", classroom); 

//Use of heap
char* classroom = malloc(10 * sizeof(*classroom));
scanf("%9s", classroom); 
//Use your variable classroom here, when done, call free to release memory.
free(classroom);

9这里是字符串长度,以防止缓冲区溢出和越界写入。数组具有10元素的大小。

于 2017-07-27T11:05:00.950 回答