简体   繁体   English

向 C 中的数组添加元素

[英]Adding elements to an array in C

I have an assignment to create a grade book with student names and grades and I'm stuck where it asks me to add a new student.我有一项任务要创建一个包含学生姓名和成绩的成绩册,但我被困在要求我添加新学生的地方。 STUDNO is where the program only allows 75 students with a NAMELENGTH of 40. STUDNO 是该计划仅允许 75 名学生的 NAMELENGTH 为 40 的地方。

So I have written a for loop to search through the array and I have no errors or warnings yet the program skips over the scanf function where it asks for name input.所以我编写了一个 for 循环来搜索数组,我没有错误或警告,但程序跳过了它要求输入名称的 scanf function。

Here is the code:这是代码:

    #define STUDNO 75
#define NAMELENGTH 40

void super(int studNo, char name [STUDNO][NAMELENGTH],
     int studMark1[STUDNO], int studMark2[STUDNO],
     int studMark3[STUDNO], int pinNo[][3])
{
    int i;
    char newName;
    int newNo;

    printf("\n      Add New Student\n");
    printf("\nPlease enter a student number: \n");
    scanf("%d", &newNo);
    printf("Please enter the student name:\n");
    scanf("%[^\n]", &newName);
    for(i = studNo-1; i >= newNo; i--)
    {
        name[STUDNO+1][NAMELENGTH]=name[STUDNO][NAMELENGTH];
    }
    name[newNo][NAMELENGTH] = newName;

This problem is very common.这个问题很常见。 When the last thing printed to the console counts as a valid input for your scanf function, it'll read that as the input or not read anything at all, not letting the user put an input into the code.当打印到控制台的最后一件事算作您的 scanf function 的有效输入时,它会将其读取为输入或根本不读取任何内容,而不是让用户将输入输入代码。 I can't get anymore technical than that because I'm not 100% sure what's happening in the scanf funtion that would cause this but to fix it, all you have to do is include the last thing you printed to the console.我无法获得更多的技术信息,因为我不能 100% 确定 scanf 函数中发生了什么会导致此问题,但要修复它,您所要做的就是包含您打印到控制台的最后一件事。 Your code would look like this.你的代码看起来像这样。

#include <stdio.h>

int main(void) {
  char newName;
  int newNo;

  printf("\nPlease enter a student number: \n");
  scanf("%d", &newNo);
  printf("Please enter the student name:\n");
  scanf("\n%[^\n]", &newName);
  printf("\n%c\n",newName); //To check if it's working
  return 0;
}

When I ran this, I noticed that this only gets you the first letter of your input so if you want the entire string, you would write the code like this.当我运行它时,我注意到这只会让你输入输入的第一个字母,所以如果你想要整个字符串,你可以这样编写代码。

#include <stdio.h>

#define NAMELENGTH 40
int main(void) {
  char newName[NAMELENGTH];
  int newNo;

  printf("\nPlease enter a student number: \n");
  scanf("%d", &newNo);
  printf("Please enter the student name:\n");
  scanf("\n%[^\n]", newName);
  printf("\n%s\n",newName); //To check if it's working
  return 0;
}

The code above can give you the following output:上面的代码可以给你以下output:

Please enter a student number:请输入学号:

40 40

Please enter the student name:请输入学生姓名:

anhtz安赫兹

anhtz安赫兹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM