C++将字符串写入文本文件中的行;新行问题不起作用
C++ writing a string to a line in a text file; New line issue not working
我正在编写一个具有许多功能的数据库程序(读取,写入,删除,搜索,登录等),而我的写作功能刚刚停止工作(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。
相关文章:
- 将新放置与 std::函数一起使用不起作用
- 从 TXT 文件中删除行不起作用
- 我的Arduino串行命令行不起作用,我不知道为什么
- 句子转换器在存在新行的情况下不起作用
- 我的二传手在新类中不起作用(继承)
- C++将字符串写入文本文件中的行;新行问题不起作用
- Python:使用<cstdio>时与c ++命令行程序的通信不起作用
- 代码行在两行后不起作用
- Visual Studio 命令行不起作用
- 向注册表添加新项不起作用
- 我的 1 行 if-else 语句不起作用
- 从文件中读取行,while(getline()) 不起作用
- 串行通信读取始终不起作用
- 我正在尝试使我的 2-D 数组程序获取每行中最大的元素,但它不起作用
- C++:STL 映射,插入新值不起作用
- 命令行有效,Makefile 中的相同命令不起作用
- 在 Arduino 环境中实例化类时串行通信不起作用
- 教授在C++中“新”的例子在我的机器上不起作用
- 矢量元素和 txt 文件行之间的字符串比较不起作用
- 在C++中读取一行之后的行不起作用