gpt4 book ai didi

C++ 将字符串写入文本文件中的一行;换行问题\n 不工作

转载 作者:太空宇宙 更新时间:2023-11-04 12:54:43 27 4
gpt4 key购买 nike

我正在编写一个具有许多功能(读取、写入、删除、搜索、登录等)的数据库程序,而我的写入功能刚刚停止工作(它在 3 天前工作),我不知道发生了什么变化。我的写入函数 (void savescore) 应该写入我的输入(cin 用户名和密码),然后移至下一行,这样我可以在下次决定写入文件时输入更多信息。现在它只是覆盖我上次输入的内容。

test2.txt -用户名、密码

然后我去编辑,输入“User, Pass”,结果是这样

test2.txt - 用户,通过

我想让它在下一行输入,我输入了“\n” 有人能帮我一些忙吗?谢谢

代码:

#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <fstream>
#include <conio.h>
#include <string>
#include <math.h>

using namespace std;

// Variables
string username;
string password;

//alphabet order functions

// Functions
void SaveScore()
{
ofstream Database;
Database.open("test2.txt");
Database << username << " " << password << "\n";


Database.seekp(0,std::ios::end); //to ensure the put pointer is at the end
Database.close();
}

int main()
{

int db;

char ans;

string save;

string file;

ifstream fin;
ofstream fout;
string searchpar;

char repeat;
bool loop = true;
while (loop == true)
{

cout << "WELCOME TO MY DATABASE\n\n";
cout << "To view the database, press 1\nTo edit the database, press 2\nTo search the database, press 3\nTo log in, press 4\n";
cin >> db;
system("CLS");

if (db == 1)
{
cout << "Here is the database: \n\n";

string line;

ifstream myfile("test2.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';

}

}

//open while bracket
cout << "\n\nWould you like to return to the menu(y/n)?";
cin >> repeat;

if (repeat == 'y')
{
loop = true;
}

else if (repeat == 'n')
{
loop = false;
}
system("CLS");

}

else if (db == 2)
{

cout << "Please enter your username : ";
cin >> username;

cout << "\nPlease enter your password: ";
cin >> password;

SaveScore();

cout << "\n\nWould you like to return to the menu(y/n)?";
cin >> repeat;

if (repeat == 'y')
{
loop = true;
}

else if (repeat == 'n')
{
loop = false;
}
system("CLS");

}
}

}

最佳答案

你说你的程序是

replacing the first line of the text file everytime I try to write something new into it

事实证明,这正是您要求它执行的操作。考虑:

Database << username << " " << password << "\n";
Database.seekp(0,std::ios::end); //to ensure the put pointer is at the end

您正在打开文件(当写指针从文件的开头开始,写入一些数据,然后寻找到结尾。寻找到结尾不会改变您已经写入文本的事实。交换以上行的顺序以获得您想要的内容。

或者,您可以使用以下方式以“追加”模式打开文件:

Database.open("test2.txt", std::ios::app);

在这种情况下,您可以完全省略对 seekp 的调用,因为所有数据都将自动写入文件末尾。参见 http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream有关这方面的完整文档。

关于C++ 将字符串写入文本文件中的一行;换行问题\n 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47086811/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com