我想通过仅将id作为输入来搜索特定行 如果id匹配文件中的id,它应该返回整行 下面的代码显示文件中的整个数据应该是什么 做一行。
我的代码如下:
void write_File()
{
ofstream file;
file.open ("example.txt");
file << "Mobile Devices \n";
file << "Name, MemorySize, Storage, ScreenSize, NetworkAdapter, MultipleCameras, Microphones \n";
file << " D01, \t 8GB, \t 32GB, \t4inches, \t Wifi, \t\t Yes, \t\t Yes \n";
file << " D02, \t 8GB, \t 16GB, \t5inches, \t Wifi, \t\t No, \t\t Yes \n";
file << " D03, \t 16GB, \t 32GB, \t4.5inches, \t Wifi, \t\t Yes, \t\t No \n";
file << " D04, \t 32GB, \t 8GB, \t4inches, \t Wifi, \t\t No, \t\t Yes \n";
file << " D05, \t 64GB, \t 8GB, \t5.5inches, \t Wifi, \t\t Yes, \t\t Yes \n";
file << endl;
file << "Personal Computer \n";
file << "Name, MemorySize, Storage, ScreenSize, PhysicalKeyboard, PointingDevices, DVDdrive, AdditionalPorts \n";
file << " PC01, \t 8GB, \t 32GB, \t12inches, \t Yes, \t\t Yes, \t\t No, \t\t 2 \n";
file << " PC02, \t 8GB, \t 16GB, \t14inches, \t Yes, \t\t No, \t\t Yes, \t\t 3 \n";
file << " PC03, \t 16GB, \t 32GB, \t16inches, \t Yes, \t\t Yes, \t\t Yes, \t\t 1 \n";
file << " PC04, \t 32GB, \t 8GB, \t14inches, \t Yes, \t\t No, \t\t No, \t\t 2 \n";
file << " PC05, \t 64GB, \t 8GB, \t12inches, \t Yes, \t\t Yes, \t\t Yes, \t\t 3 \n";
file << endl;
file.close();
}
void read_File()
{
string read;
ifstream infile;
infile.open ("example.txt");
while(!infile.eof()) // To get you all the lines.
{
getline(infile,read); // Saves the line in STRING.
cout<<read<<endl; // Prints our STRING.
}
infile.close();
}
答案 0 :(得分:0)
你可以尝试类似的东西(添加评论):
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
void PrintLineWithId(std::string id)
{
std::string read;
std::ifstream infile("example.txt");
while (infile)
{
if (std::getline(infile, read, ',')) // read beginning of the line until ,
{
if (read != id) // see if it matches id
infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // doesnt match, skip to the next line
else
{
// match
infile.seekg(size_t(infile.tellg()) - read.length() - 1); // rewind to the line beginning
std::getline(infile, read, '\n'); // read the whole line
std::cout << read << std::endl; // print
return;
}
}
}
}
int main()
{
PrintLineWithId(" D05");
return 0;
}
你必须分别处理id中的空格。
打印:
D05, 64GB, 8GB, 5.5inches, Wifi, Yes, Yes