我能够从文件中读取字符串,但是我在删除或清空该字符串时遇到了问题。 感谢您的帮助,祝您度过愉快的一天。
#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
答案 0 :(得分:1)
基本上,底层文件系统本身不支持 所以你需要手动完成。
查看您的代码:
你不应该这样做:
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;
}