這是我的嘗試:如何在windows中像gcc一樣在標準輸入中逐行讀取命令輸出?
#include <iostream>
#include <string>
int main(int argc, char const *argv[]) {
using namespace std;
for (string cin_line; getline(cin, cin_line);) {
cout << cin_line << endl;
}
FILE* pipe = popen("app.exe", "r");
for (string result_line; getline(pipe, result_line);) {
cout << result_line << endl;
}
pclose(pipe);
return 0;
}
它不能編譯,其結果是:
no matching function for call to 'getline(FILE*&, std::__cxx11::string&)'
第二個例子,我在這裏找到:https://stackoverflow.com/a/10702464/393087 但似乎MinGW的沒有包括:fatal error: pstream.h: No such file or directory
- 編輯:好吧我知道,我錯過了這不是一個海灣合作委員會圖書館,它是這樣命名,但這是單獨下載:http://pstreams.sourceforge.net/
我知道如何使用緩衝區並在單行上得到整個輸出(例如:https://stackoverflow.com/a/478960/393087),然後通過\n
爆炸該行並獲取我的數組,但這裏的要點是,我必須在輸入後立即提供輸出進來
而且我想從這裏例如:https://stackoverflow.com/a/313382/393087 - 我已經添加main
功能是:
#include <cstdio>
#include <iostream>
#include <string>
int main(int argc, char const *argv[]) {
using namespace std;
FILE * fp ;
if((fp= popen("/bin/df","r")) == NULL) {
// error processing and exit
}
ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
string s;
while (! ins.eof()){
getline(ins,s);
// do something
}
return 0;
}
這也不會編譯:
error: variable 'std::ifstream ins' has initializer but incomplete type
ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
你需要'' –
0x499602D2
2015-04-01 14:04:22
['標準:: getline'(HTTP ://en.cppreference.com/w/cpp/string/basic_string/getline)只能從C++流中讀取。要從舊的C文件流中讀取一行,您需要使用C函數['fgets'](http://en.cppreference.com/w/cpp/io/c/fgets)。 – 2015-04-01 14:04:50
至於你的第二段代碼,不要做'while(!ins.eof())',因爲這樣很少會按預期工作,因爲'eofbit'標誌在你嘗試讀取之前不會被設置從文件末尾開始,導致循環迭代一次到多次。而是使用'while(std :: getline(...))'。 – 2015-04-01 14:08:43