程序输出中的C++字符奇怪
Strange character in C++ program output
我正在为学校创建一个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();
};
帐户处理程序.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!nn";
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: NAMEnCARDNUMnPINnBALANCE
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 << "nnn";
}
谢谢!
cardNum
是一个字符串,但你给它分配了一个整数。这会将整数转换为char
(将其截断为更小的值)并将其存储在字符串中。
balance
是空的,因为它是一个空字符串,你永远不会给字符串一个值。
注意:在createAccount
中调用is_open()
是没有意义的,fstream 不能打开,因为你只是默认构造了它。
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存