我有一個讀取文件并處理它的 C++ 任務:// A.m.cpp std::string filename = "myfile.txt"; std::ifstream file(filename.c_str()); std::ifstream file1(filename.c_str()); std::string line1; while(getline(file1, line1)){ // process some logic } for(;;){ file.getline(buffer); if (file.eof()) break; // process some other logic }我有一個 python 腳本來設置測試數據并運行任務:import unittest def test_A(): file='myfile.txt' with open(file, 'w') as filetowrite: filetowrite('testdata') subprocess.run(["A.tsk"])但是,當我運行 python 腳本并執行 c++ 任務時,第一個 while 循環有效,但 for 循環只是在此處中斷 eof 的 bc :for(;;){ file.getline(buffer); // buffer is "testdata" if (file.eof()) break; // it breaks even buffer is "testdata" // process some other logic }我打印了buffer它,它有“testdata”,但是它只是在下一行中斷,所以它沒有得到處理,這不是我想要的。但是,如果我不使用 pythonsubprocess運行它,也不使用 Python 設置測試數據,而只是手動echo testdata >> myfile.txt編譯A.m.cpp和運行A.tsk,則它不會中斷 for 循環并成功處理“testdata”。出什么問題了subprocess?為什么有內容eof也會觸發?buffer
1 回答

牧羊人nacy
TA貢獻1862條經驗 獲得超7個贊
您應該在處理后放置 .eof() 中斷:
for(;;){ file.getline(buffer); // buffer is "testdata" // process some other logic if (file.eof()) break; }
即使在讀取數據后遇到 EOF,您也需要處理數據。請注意,這可能會在緩沖區中提供空字符串,因此您可能需要在處理代碼中處理這種情況。
您還需要將 python 行更改為:
filetowrite.write("testdata\n")
添加回答
舉報
0/150
提交
取消