c++ - 从 C++ 中的 .txt 文件中打印出选定的数据
问题描述
我想知道如何从文件中打印出选定的数据.txt
。
例如,这是我的input.txt
文件内容。以下样本数据的形式为[date] [error_type] [ip_address]
[Wed Oct 11 2017] [error] [127.0.0.1] -client denied.
[Thu Oct 12 2017] [alert] [127.0.0.2] -user name not found.
我被要求编写一个代码片段,它将从文件中打印出 error_type 和 ip_address。这是我的代码。
#include<iostream>
#include<fstream>
using namespace std;
int main (){
ifstream in;
in.open("input.txt");
char ch,x; //ch=[ , x=.
string er; //er=error
int a,b,c; //a=127,b=0,c=1
in>>ch>>er>>ch;
cout<<ch<<er<<ch<<ch<<a<<x<<b<<x<<b<<c<<ch;
return 0;
}
这段代码的问题是它没有读取正确的数据,只给了我随机数。
我希望有人能帮帮我,因为我刚刚学会了 4 个月的编码。所以,对我来说,一切似乎都很复杂。
解决方案
您的变量未初始化。在开始时,每个变量都可以包含每个可能的值。排队
in >> ch >> er >> ch;
你又读了一个字符、一个字符串和一个字符。
你文件的第一行是
[Wed Oct 11 2017] [error] [127.0.0.1] -client denied.
所以首先你读取第一个字符ch = '[
并将光标设置到下一个位置。接下来,您读取一个字符串,直到空格:er = "Wed"
。接下来你再读一个字符ch = 'O'
光标现在指向
[Wed Oct 11 2017] [error] [127.0.0.1] -client denied.
^
然后你打印你的数据。由于您没有阅读变量,因此您会得到随机数。
的输出
cout << ch << er << ch << ch << a << x << b << x << b << c << ch;
应该
OWedOOXCYCYZO
其中 XY 和 Z 是随机整数,C 是随机字符。
相反,您应该阅读整行并解析它(例如,在 ']' 处拆分)。您应该初始化和/或读取所有变量。x, a, b, c
没有设置。无法说出它们包含哪些值。
这是读取日志条目的可能解决方案。
#include<iostream>
#include<sstream>
using namespace std;
int main (){
stringstream in("[Wed Oct 11 2017] [error] [127.0.0.1] -client denied.\n[Thu Oct 12 2017] [alert] [127.0.0.2] -user name not found.");
string line;
getline(in, line);
int startpos = line.find('[') + 1;
int endpos = line.find(']');
string date(line.substr(startpos, endpos-startpos));
cout << "Date:\t\t" << date << endl;
startpos = line.find('[', endpos) + 1;
endpos = line.find(']', startpos);
string type(line.substr(startpos, endpos-startpos));
cout << "Type:\t\t" << type << endl;
startpos = line.find('[', endpos) + 1;
endpos = line.find(']', startpos);
string ip(line.substr(startpos, endpos-startpos));
cout << "IP:\t\t" << ip << endl;
string message(line.substr(endpos + 2));
cout << "Message:\t" << message << endl;
return 0;
}
输出
Date: Wed Oct 11 2017
Type: error
IP: 127.0.0.1
Message: -client denied.
推荐阅读
- javascript - 如何在所有页面上设置暗模式
- numpy - 如何从pyspark数据帧中提取图像到numpy
- node.js - Node Js Mongoose 如何发出更新请求
- firebase - Firebase 动态链接可靠性/可用性
- gunicorn - Google Cloud Run 上的 Gunicorn 获得 504 错误状态(上游请求超时)
- r - 通过 R 中的管道工 API 上传多个文件
- javascript - 角度路由器更改网址但不加载组件/页面
- html - 当我在大屏幕设备上时,如何使导航栏上的这个汉堡按钮消失?
- javascript - document.getElementById().style.display = "block" 与 document.getElementById().innerText 的功能不同
- python - 将 .save() 数据从 Api 直接发送到 db 会比从 Django 表单发送数据更快吗?