[英]How to store user input to array in c++
I want to build a simple program that can create data, update, and delete it.我想构建一个可以创建、更新和删除数据的简单程序。 I'm not using a database so I want to use an array for storing it.我没有使用数据库,所以我想使用一个数组来存储它。
But, I have no clue to do that.但是,我不知道这样做。 So Here my code :所以这里我的代码:
void addDataStudent() {
char name[30];
int age;
std::cout << "Name of student :";
std::cin >> name;
std::cout << "Age of student :"
std::cin >> age;
}
I want to make array something like this, so I can manipulate the data我想制作这样的数组,以便我可以操作数据
Student[] = {
[1][John, 15]
[2][Doe, 13]
}
Anybody knows how to do that ?有人知道怎么做吗? or give me a reference so I can start learning this code.或者给我一个参考,这样我就可以开始学习这段代码。 Thanks谢谢
If you want a very simple struct-based approach, that also introduces the STL, try this:如果你想要一个非常简单的基于结构的方法,它也引入了 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;
}
A lot of C++ textbooks won't introduce the STL containers till much later but I think it's better to know about them from the start.许多 C++ 教科书直到很久以后才会介绍 STL 容器,但我认为最好从一开始就了解它们。 Keep it up!保持!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.