我正在编写一个程序,我要求用户输入用户名和密码,然后将其存储在dat file
中。然后它应该输出用户名和密码,但它只给我十六进制,如0x9ffd18
。这里的代码是
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open ("password.dat");
string username;
string password;
cout << "This is being saved to a file" << endl;
cout << "Please enter your username" << endl;
getline (cin, username);
myfile << username;
cout << "Please enter your password" << endl;
getline (cin, password);
myfile << password;
cout << myfile << endl;
}
答案 0 :(得分:2)
cout << myfile << endl;
不会输出您写入文件的内容,而是void*
myfile
地址的seekg()
解释,默认打印为十六进制值。
您需要关闭文件(或{{1}}到起始位置),再次打开它,并在写入时读取值。
答案 1 :(得分:0)
我建议解决问题:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open ("password.dat", ios::in | ios::out | ios::trunc);
string username;
string password;
cout << "This is being saved to a file" << endl;
cout << "Please enter your username" << endl;
getline (cin, username);
myfile << username;
cout << "Please enter your password" << endl;
getline (cin, password);
myfile << password;
char data[100];
myfile.seekg(0,ios::beg);
myfile >> data;
cout << "Output: " << endl;
cout << data << endl;
myfile.close();
}
答案 2 :(得分:0)
这里有几个问题。一种是重写文件和回读内容的简单行为。另一个(可能更重要的是,至少从长远来看)是以一种可以明确回读的方式编写文件。
现在的问题是你写的用户名和密码没有任何东西来定义一个结束而另一个结束的地方。最明显的候选人将是一个新线。你使用getline
读取了两个,它停止在新行读取,所以我们知道两者都不能包含新行。
除此之外,我#include <string>
因为您正在使用std::string
,并且摆脱using namespace std;
和endl
(几乎总是错误)。结果可能如下所示:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::fstream myfile("password.dat", std::ios::in | std::ios::out | std::ios::trunc);
std::string username;
std::string password;
std::cout << "Please enter your username: ";
std::getline(std::cin, username);
myfile << username << '\n';
std::cout << "\nPlease enter your password: ";
std::getline(std::cin, password);
myfile << password;
myfile.seekg(0);
std::string read_back_user_name;
std::string read_back_password;
std::getline(myfile, read_back_user_name);
std::getline(myfile, read_back_password);
std::cout << "The user name is: " << read_back_user_name << "\n";
std::cout << "The password is: " << read_back_password << "\n";
}
如果你真的只想将文件的整个内容复制到cout,你可以这样做:
myfile.seekg(0);
cout << myfile.rdbuf();
答案 3 :(得分:-1)
您不会将您输入的数据打印到文件,而是将std::fstream
对象转换为地址。要解决此问题,请使用方法rdbuf()
。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open ("password.dat"); //open for input
string username;
string password;
cout << "This is being saved to a file" << endl;
getline (cin, username);
myfile << username; //input first string
cout << "Please enter your password" << endl;
getline (cin, password);
myfile << password; //input second string
myfile.close(); //close so data is sent from buffer
myfile.open("password.dat"); //open for output
cout << "Your file: " << myfile.rdbuf() << endl; //print all characterf from file
myfile.close();
}