[英]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.