我能够从文件中读取一个字符串,但是我在删除或清空该字符串时遇到了问题。 感谢您的帮助,祝您今天愉快。
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;
int main() {
map<string, string> Data; // map of words and their frequencies
string key; // input buffer for words.
fstream File;
string description;
string query;
int count=0;
int i=0;
File.open("J://Customers.txt");
while (!File.eof()) {
getline(File,key,'\t');
getline(File,description,'\n');
Data[key] = description;
}
File.close();
cout << endl;
for ( count=0; count < 3; count++) {
cout << "Type in your search query.";
cin >> query;
string token[11];
istringstream iss(Data[query]);
while ( getline(iss, token[i], '\t') ) {
token[0] = query;
cout << token[i] << endl;
i++;
}
}
system("pause");
}//end main
最佳答案
基本上底层文件系统本身不支持。
所以你需要手动完成。
- 以读取模式打开要修改的文件。
- 以写入模式打开一个临时文件。
- 从读取文件复制到写入文件。
- 不要复制要删除的行。
- 关闭两个文件
- 交换文件系统中的文件
- 删除旧文件。
查看您的代码:
你不应该这样做:
while (!File.eof())
{
getline(File,key,'\t');
getline(File,description,'\n');
Data[key] = description;
}
文件中的最后一行不会正确设置 EOF,因此您将再次进入循环,但两次 getline() 调用将失败。
几个选项:
while (!File.eof())
{
getline(File,key,'\t');
getline(File,description,'\n');
if(File) // Test to make sure both getline() calls worked
{ Data[key] = description;
}
}
// or more commonly put the gets in the condition
while (std::getline(File,line))
{
key = line.substr(0,line.find('\t'));
description = line.substr(line.find('\t')+1);
Data[key] = description;
}
关于c++ - 如何清空文件中的一行并将其写回原来的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1604487/