Printing out selected data from a .txt file in c++

时间:2018-12-19 11:20:26

标签: c++ stream

I wonder how can print out a selected data from a .txt file.

For example this is my input.txt file content. The following sample data is in the form of [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.

I was asked to write a code fragment that will printout the error_type and ip_address from file. This is my code.

#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;
}

The problem with this code is it doesn't read the right data and only gave me random numbers.

I hope anyone would lend me a hand cause I just learnt to code for 4 months. So,everything seems complicated to me.

1 个答案:

答案 0 :(得分:0)

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

in >> ch >> er >> ch;

您再次读取一个字符,一个字符串和一个字符。

文件的第一行是

[Wed Oct 11 2017] [error] [127.0.0.1] -client denied.

因此,您首先阅读第一个字符ch = '[,然后将光标设置到下一个位置。接下来,您读取一个字符串,直到空白:er = "Wed"。接下来,您再次阅读char 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

其中X Y和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.