如何才能快速入坑 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;
}