![](/img/trans.png)
[英]C++::vector of vector in `struct` as data type of another vector
[英]Printing vector of struct - data not being saved? c++
我有一個隨機生成數組的程序,然后將數字與 csv 文件中的數字進行比較。 該文件通過 getline 讀取,然后插入到我的名為“past_results”的結構中。
然后我嘗試將結構數據插入到我的主 function 中的一個向量中,但這似乎不起作用。 根本不打印任何數據。 數據的初始打印工作正常並且格式正確,但是當我發送到我的矢量時它不會從那里打印。
我正在處理一個包含整數和字符串混合的文件,所以我想知道我的數據類型管理是否是問題所在。
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
//struct to store data from file
struct past_results {
std::string date;
std::string winningnums;
};
//fills array of size 6 with random numbers between 1-50
void num_gen(int arr[])
{
for (int i = 0; i < 6; i++) {
int num = rand() % 51;
arr[i] = num;
}
}
//function to read csv
void csv_reader(){
std::string line;
past_results results;
past_results res[104];
int linenum = 0;
//open csv file for reading
std::ifstream file("path/to/csv/file", std::ios::in);
if(file.is_open())
{
while (getline(file, line))
{
std::istringstream linestream(line);
std::string item, item1;
//gets up to first comma
getline(linestream, item, ',');
results.date = item;
//convert to a string stream and put into winningnums
getline(linestream, item1);
results.winningnums = item1;
//add data to struct
res[linenum] = results;
linenum++;
}
}
//display data from struct
for(int i = 0; i < linenum; i++) {
std::cout << "Date: " << res[i].date << " \\\\ Winning numbers: " << res[i].winningnums << std::endl;
}
}
int main(){
//random num gen variables
srand(time(NULL));
int size = 6;
int numbers[size];
//fetch and print generated array of nums
num_gen(numbers);
//formatting for terminal output of random nums
std::cout<< std::endl;
std::cout << "Numbers generated: ";
for (auto i: numbers)
std::cout<< i << " ";
std::cout<< std::endl;
std::cout<< std::endl;
//call csv_reader function
csv_reader();
//create vector and insert struct data to it
std::vector<past_results> results;
results.push_back(past_results());
//printing vector of struct
for (int i = 0; i > results.size(); i++){
std:: cout << "Winning nums from struct: " << results[i].winningnums;
}
return 0;
}
CSV 格式示例:
, Date, 1, 2, 3, 4, 5, 6, 7
0, wednesday, 1, 2, 3, 4, 5, 6, 7
1, thursday, 1, 2, 3, 4, 5, 6, 7
etc...
csv_reader
寫入 function 本地數組。 一旦 function 返回,從文件中讀取的所有信息都將丟失。 數據未存儲在 class past_result
。 數據存儲在past_result
類型的實例中。
在main
中,您通過results.push_back(past_results());
作為默認構造的past_result
包含空字符串,您看不到任何輸出。
您應該將結果讀入csv_reader
中的向量並返回該向量:
std::vector<past_results> csv_reader(...) {
std::vector<past_results> result;
past_results entry;
// ...
results.push_back(entry);
// ...
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.