C/C++基础 (struct)

本文分享了适合初学者的C/C++学习指南,并通过实际代码示例介绍了如何使用g++编译器进行C/C++编程,包括结构体定义、输入输出、数据添加及列表显示等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何才能快速入坑 C/C++?曾经我也是抱着《C++ Primer 中文版》《Effective C++ 中文版》。但是对于初学者,它们并不是最好的选择,这里推荐《C/C++学习指南》一本非常适合入门的指导书。分享学习时候写的代码。

C:\Users\LAILAI\Desktop>g++ --version
g++.exe (GCC) 4.7.0 20111220 (experimental)
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

C:\Users\LAILAI\Desktop>g++ filename.cpp
// filename.cpp
#include <stdio.h>
#include <string.h>

struct Student{
	int id;
	char name[16];
	int score[3];
};

Student data[100];
int count = 0;

int test() {
	Student s;
	//input(&s);
	s.id = 1024;
	*s.name = 'w';
	*(s.name + 1) = '\0';
	*s.score = { 12 };
	*(s.score + 1) = { 22 };
	*(s.score + 2) = { 32 };
	/*
	strcpy(s.name, "SF");
	s.score[0] = { 12 };
	s.score[1] = 22;
	s.score[2] = 32;
	*/
	add(&s);
	list_all();
	return 0;
}

int input(Student* s) {
	printf("ID: ");
	scanf("%d",&s->id);
	printf("Name:");
	//char a;
	//getchar();
	scanf("%s",s->name);
	//a = getchar();
	//gets_s(s->name);
	//a = getchar();
	printf("Score: ");
	scanf("%d,%d,%d", &s->score[0], &s->score[1], &s->score[2]);
	return 0;
}

int add(Student* s) {
	data[count] = *s;
	count++;
	return 0;
}

void list_all() {
	for (int i = 0; i < count; i++) {
		Student* s = &data[i];
		printf("%d \t%s \t %d,%d,%d \n", 
		s->id, s->name, s->score[0], s->score[1], s->score[2]);
	}
}

Student* find(const char* name) {
	for (int i = 0; i < count; i++) {
		Student* s = &data[i];
		if (strcmp(name, s->name) == 0) {
			return s;
		}
	}
	return NULL;
}


int main() {
	char cmdline[128];
	while (1) {
		printf(">");
		scanf("%s", cmdline);
		//printf("cmd: %s \n",cmdline);

		if (strcmp(cmdline, "exit") == 0) {
			printf("now exit...\n");
			break;
		}
		if (strcmp(cmdline, "add") == 0) {
			Student s;
			input(&s);
			add(&s);
			continue;
		}
		if (strcmp(cmdline, "count") == 0) {
			printf("total: %d \n",count);
			continue;
		}
		
		if (strcmp(cmdline, "find") == 0) {
			printf("Name: ");
			char name[16];
			scanf("%s",name);
			Student* s = find(name);
			if (s) {
				printf("Found: ID: %d ,Name: %s,Scores:%d,%d,%d", s->id,s->name, s->score[0], s->score[1], s->score[2]);
			}
			else {
				printf("Not Found\n");
			}
			continue;
		}
		if (strcmp(cmdline, "list") == 0) {
			list_all();
			continue;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值