我在将用户输入保存到Txt文件时遇到问题。不确定我做错了什么;它没有写入文件:
void Menu::nowShowingDecisions()
{
switch (userInput)
{
case 1:
system("cls");
xyPosition(0, 0);
CAtitleHeader();
CAtitleMenu();
getUserInput();
CAtitleDecisions();
break;
return;
case 2:
{
string userName;
string password;
{
ofstream outFile;
{
outFile.open("C:\\Test\\Test.txt");
if (!outFile.good())
cout << "File Could Not Be Opened." << endl;
else
{
cout << "Enter Username:";
cin >> userName;
cout << "Enter Password:";
cin >> password;
while (cin >> userName >> password)
outFile << userName << password << endl;
outFile.close();
}
}
}
return;
{
const int COL_SZ = 10;
ifstream inFile;
inFile.open("C:\\Test\\Test.txt");
if (!inFile.good())
cout << "File could not be opened" << endl;
else
{
cout << left;
cout << "Movie Ticket Accounts" << endl;
cout << setw(COL_SZ) << "User Name" << setw(COL_SZ) << "Password" << endl;
while (inFile >> userName >> password)
{
cout << setw(COL_SZ) << userName << setw(COL_SZ) <<
password << setw(COL_SZ) << endl;
}
inFile.close();
return;
}
}
}
break;
答案 0 :(得分:0)
在这段代码中
cout << "Enter Username:";
cin >> userName; // BEING IGNORED
cout << "Enter Password:";
cin >> password; // BEING IGNORED
while (cin >> userName >> password) // THIS IS BEING SAVED>
outFile << userName << password << endl;
您没有将第一个userName
和password
写入输出文件。
目前尚不清楚你是否真的想要while
循环。如果您只想写出第一个用户名和密码,则需要将其更改为:
cout << "Enter Username:";
cin >> userName;
cout << "Enter Password:";
cin >> password;
if (cin)
outFile << userName << password << endl;
答案 1 :(得分:0)
使用C ++读取或写入txt可以通过这样的简单方式完成。
//在文本文件上书写
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
//读取文本文件
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}