首页 > 解决方案 > 从 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 个月的编码。所以,对我来说,一切似乎都很复杂。

标签: c++stream

解决方案


您的变量未初始化。在开始时,每个变量都可以包含每个可能的值。排队

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.

推荐阅读