I'm able to read a string from a file but I'm having trouble deleting or emptying that string. Thanks you for helping and have a great day.
#include <iostream&g开发者_如何学Pythont;
#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
Basically the underlying file system does not support that natively.
So you need to do it manually.
- Open the file you want to modify in read mode.
- Open a temporary file in write mode.
- Copy from the read file into the write file.
- Don't copy the line you want to delete.
- Close both files
- Swap the files in the file system
- Delete the old file.
Looking at your code:
You should not be doing this:
while (!File.eof())
{
getline(File,key,'\t');
getline(File,description,'\n');
Data[key] = description;
}
The last line in the file will not set the EOF correctly thus you will enter the loop again but the two getline() call will fail.
A couple of options:
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;
}
精彩评论