我想讀取一個包含文本和數字的文本檔案,在讀取它之后,將該檔案中的一些資料寫入一個僅包含每行最后 3 個數字的新文本檔案中。如果有“120,你好,嗨”的文字,我想跳過它,只寫“嗨”后的最后3個數字,寫完這3個數字后換行。這里我使用字串向量來讀取它,但是我無法獲得我想要寫入的格式。我怎樣才能把它寫成我想要的格式?任何幫助,將不勝感激。
輸入文本檔案:"mytext.txt"
120
你好
嗨 55 66 44
嗨 1 2 3
嗨 11 22 33
嗨 111 222 333
想要的格式:“mynewtext.txt”
55 66 44
1 2 3
11 22 33
111 222 333
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector<string> VecData;
string data;
ifstream in("mytext.txt");
while (in >> data) {
VecData.push_back(data);
}
in.close();
ofstream mynewfile1("mynewtext.txt");
for (int i = 0; i < VecData.size(); i ) {
if ((VecData[i] != "120") || (VecData[i] != "Hello") || (VecData[i] != "Hi")) {
mynewfile1 << VecData[i] << " ";
}
}
mynewfile1.close();
return 0;
}
uj5u.com熱心網友回復:
這里的問題是您正在檢查這VecData[i]不是"120",或者不是"Hello",或者不是"Hi"。這將永遠是true。
想一想 where VecData[i]is的情況"Hi":
if ((VecData[i] != "120") || // (1)
(VecData[i] != "Hello") ||
(VecData[i] != "Hi"))
比較 at(1)已評估為 True,因為"Hi" != "120"。
您應該做的是檢查它不是“120”,不是“Hello”,也不是“Hi”,如下所示:
if ((VecData[i] != "120") &&
(VecData[i] != "Hello") &&
(VecData[i] != "Hi"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321791.html
