c语言

c语言怎么实现修改功能

小亿
182
2024-04-20 09:31:10
栏目: 编程语言

要实现修改功能,首先需要获取用户输入的数据,并根据用户输入的信息找到对应的数据进行修改。以下是一个简单的示例代码来实现修改功能:

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

struct Student {
    char name[50];
    int age;
};

int main() {
    struct Student students[10];
    int numStudents = 0;
    int choice, index;
    
    do {
        printf("\n1. Add student\n");
        printf("2. Modify student\n");
        printf("3. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        
        switch(choice) {
            case 1:
                printf("\nEnter student name: ");
                scanf("%s", students[numStudents].name);
                printf("Enter student age: ");
                scanf("%d", &students[numStudents].age);
                numStudents++;
                break;
                
            case 2:
                printf("\nEnter index of student to modify (0-%d): ", numStudents-1);
                scanf("%d", &index);
                if (index >= 0 && index < numStudents) {
                    printf("Enter new name for student: ");
                    scanf("%s", students[index].name);
                    printf("Enter new age for student: ");
                    scanf("%d", &students[index].age);
                } else {
                    printf("Invalid index\n");
                }
                break;
                
            case 3:
                break;
                
            default:
                printf("Invalid choice\n");
        }
    } while (choice != 3);
    
    printf("\nList of students:\n");
    for (int i = 0; i < numStudents; i++) {
        printf("%d. %s, %d\n", i, students[i].name, students[i].age);
    }
    
    return 0;
}

这段代码定义了一个学生结构体Student,可以添加学生信息和修改学生信息。用户可以选择添加学生信息、修改学生信息或退出程序。程序会一直运行直到用户选择退出。

0
看了该问题的人还看了