Search code examples
c++fileunsigned-long-long-int

c++: long long int won't write to file


Small program designed to allow users to update their details.

All variables initialized in the get functions and get functions are all called before any of the set functions functions called:

int File::Getline1()
{
    std::string filename = std::to_string(user1);

    std::ifstream fin(filename + ".txt");
    fin.getline (line1, 5);
    fin.close();

    user1 = (atoi(line1));

    return user1;
}

int File::Getline2()
{
    std::string filename = std::to_string(user1);

    std::ifstream fin(filename + ".txt");
    fin.getline (line1, 5);
    fin.getline (line2, 5);
    fin.close();

    user2 = (atoi(line2));

    return user2;
 }

long long int File::Getline3()
{
    std::string filename = std::to_string(user1);

    std::ifstream fin(filename + ".txt");
    fin.getline (line1, 5);
    fin.getline (line2, 5);
    fin.getline (line3, 20);
    fin.close();

    char* endptr = NULL;
    return strtoll(line3, &endptr, 10);
}

int File::Getline4()
{
    std::string filename = std::to_string(user1);

    std::ifstream fin(filename + ".txt");
    fin.getline (line1, 5);
    fin.getline (line2, 5);
    fin.getline (line3, 20);
    fin.getline (line4, 5);
    fin.close();

    user4 = (atoi(line4));

    return user4;
}

Which set functions are called is dependent on a series of if statements elsewhere, with SetFile() being called after the if statements.

If Setline3_4 is called, everything is written to the file correctly. However if Setline1 or Setline2 is called, everything writes to file correctly except for user3, which is written as "-3689348814741910324", - user1, user2 and user4 however are written correctly.

I cannot figure out why (note: all user variables are ints, except for user3 which is a long long int - I think maybe the issue lies here?)

void File::Setline1()
{
    user5 = user1;
    filename = std::to_string(user5);
    remove((filename + ".txt").c_str());

    std::cout << "Enter Line 1: ";
    std::cin >> user1;
}

void File::Setline2()
{
    std::cout << "Deposit (can be 0): ";
    std::cin >> deposit;
    std::cout << "\nWithdraw (can be 0): ";
    std::cin >> withdraw;

    user2 = ((user2 + deposit) - withdraw);
}

void File::Setline3_4()
{
    std::cout << "Card Number: ";
    std::cin >> user3;

    std::cout << "Card Expiry date: ";
    std::cin >> user4;
}

void File::Setfile()
{   
    std::string filename = std::to_string(user1);

    std::ofstream fout(filename + ".txt");
    fout << user1 << std::endl << user2 << std::endl << user3 << std::endl << user4 << std::endl;
    fout.close();
}

Solution

  • Because user3 is not initialized. So, it contains some junk value. Just initialize it to avoid junk value printed.

    long long user3 = 0 ; // where you have declared user3 in the program.