F4QU
F4QU

Reputation: 1

Reading from .csv file

I am trying to save variables in .csv file, even after closing the program and then when opening again to read them from the .csv so, the variables won't reset after closing. The $balance works fine, but $level and $cases's values are 1 every time. They are saved in the .csv, but I can't read them.

#include <iostream>
#include <random>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;

int main() {
  int $balance = 0, $new_balance, $bet_amount, $random_number, $multiplies, $number_type_number, case_opening;
  int $level = 1, $cases = 1, $xp = 0;
  int $input_balance = 0, $input_level = 1, $input_cases = 1;
  string $free_coins, $bet_type, $number_type_color, $number_type_odd_even, $number_type_row, $bet_type_color;
  string $bet_type_halves, $bet_type_third, $bet_type_row;
  string $roll_again;
  ofstream myFile;
  ifstream inputFile;
  string line, line1, line2;

  /*Useless Code*/

  inputFile.open("database.txt");

  while (getline(inputFile, line)) {
    istringstream ss(line);
    ss >> $input_balance;
    $balance = $input_balance;  
  }

  while (getline(inputFile, line1)) {
    istringstream ss1(line1);
    ss1 >> $input_level;
    $level = $input_level;
  }

  while (getline(inputFile, line2)) {
    istringstream ss2(line2);
    ss2 >> $input_cases;
    $cases = $input_cases;
  }
    
  do {
   /*More Useless Code*/
   myFile.open("database.txt");
   myFile << $balance << "\t" << $level << "\t" << $cases;
   myFile.close();
  } while($roll_again == "yes" || $roll_again == "y" || $roll_again == "Yes" || $roll_again == "Y");
}

Upvotes: 0

Views: 83

Answers (1)

Jim Rhodes
Jim Rhodes

Reputation: 5085

  1. You don't check to see if the open() calls are successful.
  2. You don't close inputFile before writing to myFile. How do you know that writes to the file will work when it is already open for reading?
  3. Why are you using while (getline(inputFile, line)). That doesn't make sense. The value of every line will get assigned to $balance.
  4. You are writing tabs ("\t") to the file instead of newlines ("\n") so all three values will be on one line.
  5. Your final loop will never exit if $roll_again is y,Y,yes or Yes. But you never assign a value to $roll_again anyway so why the loop?

Upvotes: 1

Related Questions