如何在C ++中逐行读取管道命令?

时间:2014-03-27 08:59:43

标签: c++ shell stdin

我有一个名为example.cpp的cpp程序。在这个程序中,我想逐行读取stdin并将每一行保存在一个字符串中。但它不是来自关键字或文件。输入来自命令行:

CC example.cpp -o ALO
last -n 10 | ./ALO

我尝试了以下几种方法但不适用于此:

for (std::string line; std::getline(std::cin, line);) {
    std::cout << line << std::endl;
}


return 0;

char name[256];
while (cin.getline (name,256))
{
    cout << "Got " << name << endl;
}

string name;
while (getline(cin, name))
{
    cout << "Got " << name << endl;
}

更新

我目前得到的输出是

Got sshd
Got 192.131.251.2
Got Thu
Got Mar
Got 27
Got 18:16
Got -
Got 18:17
Got (00:00)
Got dwm914
Got sshd
Got mega-pc21.cs.uow
Got Thu
Got Mar
Got 27
Got 18:16
Got -
Got 18:17
Got (00:01)
Got tb713
Got pts/71
Got 192.131.251.2
Got Thu
Got Mar
Got 27
Got 18:15
Got -
Got 18:16
Got (00:01)
Got tb713
Got sshd
Got 192.131.251.2
Got Thu
Got Mar
Got 27
Got 18:15
Got -
Got 18:16
Got (00:01)

期望的输出:

bkg988    sshd         139.218.157.100  Thu Mar 27 20:00 - 20:00  (00:00)
sh615     sshd         cpe-121-216-173- Thu Mar 27 19:57 - 19:59  (00:01)
sh615     sshd         cpe-121-216-173- Thu Mar 27 19:57 - 19:59  (00:01)

0 个答案:

没有答案