我們得到了一個帶有:“6=3 3”的 txt 檔案,我想將字串決議為兩個,例如:“6=”和“3 3”。之后我想將所有內容保存在結構中,而不是陣列中,而是結構中。任何的想法?
uj5u.com熱心網友回復:
在下面的程式展示了如何分離出LHS(左側)和RHS(右手邊),并將其存盤在一個結構物件。
#include <iostream>
#include <sstream>
#include<fstream>
struct Equation
{
std::string lhs, rhs;
};
int main() {
struct Equation equation1;//the lhs and rhs read from the file will be stored into this equation1 object's data member
std::ifstream inFile("input.txt");
if(inFile)
{
getline(inFile, equation1.lhs, '=') ; //store the lhs of line read into data member lhs. Note this will put whatever is on the left hand side of `=` sign. If you want to include `=` then you can add it explicitly to equation.lhs using `equation1.lhs = equation1.lhs "="`
getline(inFile, equation1.rhs, '\n'); //store the rhs of line read into data member rhs
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//print out the lhs and rhs
std::cout<<equation1.lhs<<std::endl;
std::cout<<equation1.rhs<<std::endl;
return 0;
}
程式的輸出可以在這里看到
uj5u.com熱心網友回復:
您可以為結構創建 2 個字串成員,一個 RHS 和一個 LHS。然后你可以創建一個成員函式,它接受一個字串引數(要決議的方程),或者你可以使用 for 回圈遍歷字串檢查等號,一旦找到它,它就會將迭代部分存盤到LHS 并繼續迭代器并將其余部分存盤在 RHS 中。
或者
您可以像這樣將字串決議為字串流:
std::stringstream stream;
stream << equation;
然后使用帶有“=”分隔符的 std::getline 并像這樣分隔字串。有比這更多的方法來做到這一點。嘗試自己做!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/339415.html
上一篇:匯出帶有自定義圖示的exe
