c++ - 从另一个文件c ++访问变量值
问题描述
我正在做一些需要密码的事情。
现在我可以创建文件并在其中存储自定义用户输入,但我似乎无法在任何地方找到如何使用用户创建的值存储变量,并使其在下次程序启动时能够读取该文件并了解其价值。
#include "stdafx.h"
#include "string"
#include "iostream"
#include "fstream"
#include "windows.h"
using namespace std;
int main() {
string user;
string pass;
string entry;
std::ifstream f("test.txt");
if (f.fail()) {
std::ofstream outfile("test.txt");
cout << "Please make a username.\n";
cin >> user;
cout << "Please make a password.\n";
cin >> pass;
outfile << user << std::endl;
outfile << pass << std::endl;
outfile.close();
cout << "Please restart.\n";
int x = 3000;
Sleep(x);
}
else {
cout << "please enter username\n";
cin >> entry;
if (entry == user) {
cout << "Welcome";
int x = 3000;
Sleep(x);
}
else if (entry != user) {
cout << "Nope";
int x = 3000;
Sleep(x);
}
}
return 0;
}
解决方案
您还没有添加必要的代码来读取保存的用户名和密码。在else
函数部分,添加
f >> user;
f >> pass;
作为前两行。
else {
// Read the user name and password from the file.
f >> user;
f >> pass;
cout << "please enter username\n";
cin >> entry;
if (entry == user) {
cout << "Welcome";
int x = 3000;
Sleep(x);
}
else if (entry != user) {
cout << "Nope";
int x = 3000;
Sleep(x);
}
}
推荐阅读
- html - 使用样式属性动态设置css变量不起作用,Angular 8
- mule - 使用 Dataweave 拆分表列中的串联值
- java - LocalDate 的 Mapstruct 默认值
- r - 如何知道一个数字是否在R中的确定区间内
- java - 将枚举模式视为对象(而不是字符串)
- sql - 如何 SAFE_CONVERT_BYTES_TO_STRING 和 REPLACE?
- python - 如何拆分 os.path.basename 的输出并在创建 yaml 字典时只在同一行中获取唯一输出?
- postman - 如何使用 Postman 中的数据文件设置环境变量
- python - 使用 Tensorflow 加载 AutoML 生成的模型会引发“操作类型未注册 'ParseExampleV2”
- firebase - 使用 gcloud 服务帐户登录到 Firebase