[英]Getting different data types from a text document and storing it into vectors? C++
我有一項任務我應該完成,並且確實需要一些幫助來掌握和理解某些概念。
基本上我們的任務是創建一個名為students.txt的文檔,我們將通過這種格式存儲一堆學生信息:
例子:
1387歷史4.0
3984 科學 2.3
該程序基本上可以通過用戶輸入他們的ID,專業和GPA來創建新學生,並將其存儲在下面的一行中。 我在理解如何格式化某些內容方面遇到了一些問題。 我目前有這個:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main(){
std::ofstream studentFile{ "students.txt", std::ios::app };
int studentID;
string major;
double gpa;
cout << "ID #: ";
cin >> studentID;
cout << "Major: ";
cin >> major;
cout << "GPA: ";
cin >> gpa;
studentFile << studentID << " ";
studentFile << major << " ";
studentFile << gpa << " " << endl;
studentFile.close();
return 0;
}
我還擔心我將如何執行程序的一項功能,該功能要求您在用戶輸入時顯示文件的給定內容。 提示是程序運行時,主function會有向量,每個向量代表文檔的每一列,以后可以使用。 這是我無法理解的程序,每個向量將如何讀取並知道要存儲什么以及如何存儲,以便以后如果用戶僅通過他們的 ID 要求刪除學生,則有關該 ID 的信息的 rest 將是也被刪除了。
如:刪除學生:3984
或者當被問及用戶要求在它顯示的文檔上顯示當前信息時:
3728 生物學 3.6 8372 數學 2.4 2933 科學 3.4
對於顯示部分,我有這個:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(){
ifstream studentFile;
studentFile.open("students.txt");
vector<int> student_ids;
std::vector<std::string> student_majors;
vector<float> student_gpas;
int data;
while (studentFile >> data) {
student_ids.push_back(data);
}
studentFile.close();
cout << student_ids[0] << endl;
cout << student_ids[1] << endl;
cout << student_ids[2] << endl;
return 0;
}
我知道這是不正確的,但我試圖掌握如何從文本文檔中獲取數據並將每個數據存儲到特定的向量中,以便文檔中的 ID 將存儲在向量 student_ids 中,major 向量中的專業等等
任何幫助或提示都意味着世界,謝謝你的時間:)
制作3個向量是錯誤的。 更好的方法是生成一個學生 class:
class Student {
public:
int id;
std::string major;
double gpa;
};
然后你可以定義你的向量:
std::vector<Student> students;
這樣,您可以將有關單個學生的所有數據保存在一個整潔的小 package 中。
然后,您需要有一個 for 循環,從輸入文件中讀取行,將數據粘貼到 Student object 中,然后將其推送到向量中。
從你的代碼的這個結構開始,看看你是否能走得更遠。
但是,您已經討論過遍歷三個向量。
vector<int> vec1;
vector<string> vec2;
vector<double> vec3;
... Assume you populate them equally so they're all the same size
for (size_t index = 0; index < vec1.size(); ++index) {
int thisA = vec1.at(index);
string thisStr = vec2.at(index);
double thisDouble = vec3.at(index);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.