C++将字符串写入文本文件中的行;新行问题不起作用

C++ writing a string to a line in a text file; New line issue not working

本文关键字:新行 不起作用 问题 文件 字符串 文本 C++      更新时间:2023-10-16

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

测试2.txt -用户名、密码

然后我去编辑并输入"用户,通过",这就是发生的事情

测试2.txt - 用户,通过

我希望它在下一行输入它,我做了""有人可以给我一些帮助吗?谢谢

法典:

#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 DATABASEnn";
        cout << "To view the database, press 1nTo edit the database, press 2nTo search the database, press 3nTo log in, press 4n";
        cin >> db;
        system("CLS");
        if (db == 1)
        {
            cout << "Here is the database: nn";
            string line;
            ifstream myfile("test2.txt");
            if (myfile.is_open())
            {
                while (getline(myfile, line))
                {
                    cout << line << 'n';
                }
            }
            //open while bracket
            cout << "nnWould 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 << "nnWould you like to return to the menu(y/n)?";
            cin >> repeat;
            if (repeat == 'y')
            {
                loop = true;
            }
            else if (repeat == 'n')
            {
                loop = false;
            }
            system("CLS");
        }
    }
}

你说你的程序是

每次我尝试在其中写入新内容时替换文本文件的第一行

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

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。