如何搜索文本文件并以C++打印该行

How to search a text file and print that line in C++

本文关键字:C++ 打印 文件 文本 何搜索 搜索      更新时间:2023-10-16

我正在尝试制作一个程序,要求用户输入文本文件名,一旦打开,就会要求用户输入一个星号名称,它将在文件中查找并在该行上打印信息。 这对大多数人来说可能是显而易见的,但是每当我打开文件并输入星号名称时,都会打印出整个文本文件。有人能告诉我哪里出错了,为什么它不只是打印行而不是整个文件?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream input;
string fileName, starName, Name, ProperName, HRnumber, HDnumber, distance;
cout << "Enter the file name >> ";
cin >> fileName;
input.open(fileName.c_str());
if(input.is_open())
{
cout << "Enter star proper name >> " ;
cin >> starName;
while(getline(input, starName, '~'))
{
cout << starName << ' ' << Name << ' ' << ProperName << ' ' << HRnumber<< ' '  << HDnumber<< ' '  << distance;
}
}
else
{
cout << "The file "" << fileName << "" does not exist.";
}
input.close();
}

首先,函数std::getline(input,targetstr,delim)input读取到字符串targetstr的完整行,而delim告诉函数将哪个字符视为行尾。由于您传递的是字符'~',并且我认为您的文件不包含任何~,那么第一个getline调用会将整个文件读取为变量starName。打印starName时,会打印完整的文件内容。

修复此问题后,请注意,您不会解析读入的行,也不会检查它是否在感兴趣的行,并且在访问变量时打印空字符串Name,...等等。没有魔术可以按预期将行内容映射到变量,也没有魔术可以检查您是否在感兴趣的行上。

因此,从以下开始作为起点;回到SO一个,你又被卡住了:

std::string line;
while(getline(input, line))  // use default line endings, i.e. 'n'
{
// check if line starts with starName (your job to try):
if (...) {
// parse the contents of the line (you job to try): 
}
}
getline

存在问题,可能是使用了文件中不存在的~。 请参考此示例:

std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!n";

在您的情况下starName打印文件的全部内容。

希望这有帮助。