简体   繁体   中英

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.

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.

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. 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. 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:

Please enter a student number:

40

Please enter the student name:

anhtz

anhtz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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