[英]How to store user input to array in c++
我想构建一个可以创建、更新和删除数据的简单程序。 我没有使用数据库,所以我想使用一个数组来存储它。
但是,我不知道这样做。 所以这里我的代码:
void addDataStudent() {
char name[30];
int age;
std::cout << "Name of student :";
std::cin >> name;
std::cout << "Age of student :"
std::cin >> age;
}
我想制作这样的数组,以便我可以操作数据
Student[] = {
[1][John, 15]
[2][Doe, 13]
}
有人知道怎么做吗? 或者给我一个参考,这样我就可以开始学习这段代码。 谢谢
如果你想要一个非常简单的基于结构的方法,它也引入了 STL,试试这个:
#include <iostream>
#include <array>
//read about structs; the typedef is here so we can refer to this type simply as 'Data'
typedef struct data{
std::string name;
int age;
} Data;
//note the & means pass-by-reference so we reduce copying expenses
void addStudent(Data& store) {
std::cout << "Enter name: ";
std::cin >> store.name;
std::cout << "Enter age: ";
std::cin >> store.age;
}
int main() {
const int SIZE = 3;
std::array<Data, SIZE> Students {}; // STL fixed-size array (see std::vector also)
for (int i = 0; i < SIZE; ++i) {
addStudent(Students[i]); //this (a struct inside the array) gets passed
} //to the function by reference
for (auto student : Students) { //here we display contents of container
std::cout << student.name << " " << student.age << std::endl;
}
return 0;
}
许多 C++ 教科书直到很久以后才会介绍 STL 容器,但我认为最好从一开始就了解它们。 保持!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.