结构的打印向量 - 数据未保存? C++

Printing vector of struct - data not being saved? c++

我有一个随机生成数组的程序,然后将这些数字与 csv 文件中的数字进行比较。该文件通过 getline 读取,然后插入到我的名为 'past_results'.

的结构中

然后我尝试将结构数据插入到我的主函数中的向量中,但这似乎不起作用。根本不打印任何数据。数据的初始打印工作正常并且格式正确,但是当我发送到我的矢量时它不会从那里打印。

我正在处理一个混合了整数和字符串的文件,所以我想知道是不是我的数据类型管理出了问题。

#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 写入函数局部数组。一旦函数 returns 从文件中读取的所有信息都将丢失。数据未存储在 class past_result 中。数据存储在 past_result.

类型的实例中

main 中,您通过 results.push_back(past_results()); 将单个元素推送到向量,因为默认构造 past_result 包含您看不到输出的空字符串。

您应该将结果读入 csv_reader 和 return 中的向量,该向量:

std::vector<past_results> csv_reader(...) {
      std::vector<past_results> result;
      past_results entry;
      // ...
            results.push_back(entry);
      // ...
      return result;
}