c语言输入学号重复再次输入

c语言输入学号重复再次输入,第1张

最简单的就是用链表保存每个学号,当输入新学号时遍历整个链表:

#define ID_LEN 20
typedef struct Student{
    char id[ID_LEN];
    // 其他你需要的数据
    struct Student next;
} Student;
void foo(Student list)
{
    if(list == NULL) return;
    
    char buf[ID_LEN];
    Student p;
    
    while(fgets(buf, ID_LEN, stdin) != NULL) {
        buf[strlen(buf) - 1] = '\0';
        p = list;
        while(p != NULL && strcmp(p->id, buf) != 0)
            p = p->next;
        if(p == NULL)  // 未找到重复学号,直接退出
            return;
    }
}

C语言中实现多组数据输入输出主要有两种方式:

1首先输入一个n,表示将有n个输入输出,例如:

#include <stdioh>
int main()
{
    int n,a;
    scanf("%d",&n);
    while(n--){
    scanf("%d",&a);
    printf("输出:%d\n",a);
    }    
return 0;
}
/
运行结果:
3
255
输出:255
156
输出:156
125
输出:125 
/

2使用while(scanf("%d",&n)!=EOF){}语句,直达输入ctrl+z,结束输入,例如:

#include <stdioh>
int main()
{
    int a;
    while(scanf("%d",&a)!=EOF){
    printf("输出:%d\n",a);
    }    
return 0;
}
/
运行结果:
54
输出:54
5156
输出:5156
21
输出:21
^Z
/

C的数组是不可以动态增长,如果你不想使用链表,可以参考下面方法。

1、用malloc分配一块空间,比如int a = (int) malloc( 10sizeof(int) );
然后可以当成好像是数组一样使用,比如a[2] = 5;

2、然后你需要增长的时候,就用realloc( a, 20sizeof(int))扩展空间。不过每一次扩展都会有一次拷贝,相当于分配一块新的空间,然后把原来的数据拷贝过去,所以数组大了以后,速度会很慢。

3、使用while(scanf("%d",&n)!=EOF){}语句,直达输入ctrl+z,结束输入,例如:

#include <stdioh>
int main()
{
    int a;
    while(scanf("%d",&a)!=<a href=">

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12688713.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-27
下一篇 2023-05-27

发表评论

登录后才能评论

评论列表(0条)

保存