如何搜索文本文件并以C++打印该行
How to search a text file and print that line in C++
我正在尝试制作一个程序,要求用户输入文本文件名,一旦打开,就会要求用户输入一个星号名称,它将在文件中查找并在该行上打印信息。 这对大多数人来说可能是显而易见的,但是每当我打开文件并输入星号名称时,都会打印出整个文本文件。有人能告诉我哪里出错了,为什么它不只是打印行而不是整个文件?
#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
打印文件的全部内容。
希望这有帮助。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数