【问题标题】:Strange character in C++ program outputC ++程序输出中的奇怪字符
【发布时间】:2016-03-15 14:20:06
【问题描述】:

我正在用 C++ 为学校创建一个 ATM 程序,并利用这个项目作为开始学习该语言的机会。我正在尝试以这种格式将银行帐户输出到文本文件:

First Last  
CardNumber  
PinNumber  
Balance

最初它输出正常,然后我开发了一堆新方法等。我没有更改任何与输出银行帐户有关的原始代码,但现在输出很奇怪。

我的输出最终是:

First Last  
random letter or symbol  
PinNumber  
blank  

这是我创建新银行帐户的代码:

AccountHandler.h

#include <iostream>
#include <string>

using namespace std;

struct bankAccount //Create a new bank account type
{
string name;
string cardNum;
string balance;
string pin;
};



class AccountHandler
{
public:

    AccountHandler();
    ~AccountHandler();
    void withdraw(struct bankAccount acc, string amount);
    void deposit(struct bankAccount acc);
    int checkBalance(struct bankAccount acc);
    void createAccount();


};

AccountHandler.cpp

void AccountHandler::createAccount() //creates a new bank account and stores in accounts.txt
{
ofstream accounts;
struct bankAccount newAcc;
string first, last;
string tempPin1, tempPin2;

if (!accounts.is_open())
{
    accounts.open("accounts.txt", ofstream::app);
}

std::cout << "Thank you for choosing to bank with ATM406!\n\n";
std::cout << "Please enter the name for the account: ";
std::cin >> first >> last;
newAcc.name = first + " " + last;

while (true)
{

    std::cout << "\nPlease enter a 4-digit pin for security: ";
    std::cin >> tempPin1;

    std::cout << "\nPlease re-enter your 4-digit pin for validation: ";
    std::cin >> tempPin2;

    if (tempPin1 == tempPin2) //PINS MATCH
    {
        newAcc.pin = tempPin1;
        break;
    }
    else //PINS DO NOT MATCH
    {
        std::cout << "The pins did not match!" << std::endl;
    }

}

//GENERATE A RANDOM 4-DIGIT NUMBER FOR CARDNUM

srand(time(NULL));
newAcc.cardNum = rand() % 9000 + 1000;


//STORE ACCOUNT IN FORMAT: NAME\nCARDNUM\nPIN\nBALANCE

accounts << newAcc.name << "\n" << newAcc.cardNum << "\n" 
    << newAcc.pin << "\n" << newAcc.balance << "\n";

accounts.close();

std::cout << "\nAccount created with name: " << newAcc.name << "  pin: " << newAcc.pin
    << ". Card number: " << newAcc.cardNum << "\n\n\n";


}

谢谢!

【问题讨论】:

  • 你如何更新bankAccount::balance ?我在发布的代码中没有看到。
  • newAcc.cardNum = rand() % 9000 + 1000; 看起来很可疑。参见例如stackoverflow.com/questions/4668760/… 如果要将整数转换为 std::string

标签: c++ iostream


【解决方案1】:

cardNum 是一个字符串,但您为其分配了一个整数。这会将整数转换为 char(将其截断为更小的值)并将其存储在字符串中。

balance 是空白的,因为它是一个空字符串,你永远不会给字符串一个值。

注意在createAccount 中调用is_open() 毫无意义,fstream 无法打开,因为您只是默认构造了它。

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多