c - 尝试将字符串扫描到c中结构的2个不同元素

标签 c arrays string struct scanf

我尝试将 2 个不同的字符串扫描到同一结构的 2 个不同元素,但我不知道为什么它不起作用。

这是我的代码:

struct qRegStudents{
  char studID[6];
  char studName[25];
};

typedef struct qRegStudents students;

int RegStudent() {
  students Student;
  char temp[6];

  printf("Enter ID Number: ");
  scanf(" %6s",Student.studID);
  printf("Enter Name: ");
  scanf(" %25s",Student.studName);

  printf("%s",Student.studID);

  return 0;
}

我输入的学生 ID 为“123456”,然后姓名为“josh”。它打印“123456josh”作为学生 ID

最佳答案

您没有在 studID 字段中分配足够的空间来容纳 6 个字符加上空终止符。将定义更改为:

struct qRegStudents{
    char studID[7];
    char studName[25];
};

编辑...最好在 printf 字符串末尾包含 \n 以确保其刷新到标准输出。

关于c - 尝试将字符串扫描到c中结构的2个不同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049153/

相关文章:

c - C99 是否保证数组是连续的?

c - voronoi 图不正确

java - 将 VB.NET 转换为 C、C++ 或 Java

c++ - 尝试打印存储在 C++ 类型对象数组中的信息

string - Tcl在字符串末尾添加一个符号N次

c# - 互操作将字符串从 C# 发送到 C++

c++ - 使用临时 volatile 限定符优化共享数组访问

javascript - 如何从setState中的数组中选择特定对象?

sql - 在 SQL Server 中从 JSON 中的数组获取值

python - 如何验证字符串?