[英]C++ - How to get strings from a file to be saved as separate strings
對此我有任何幫助,不勝感激。
對於這個項目,我們必須首先從文件中獲取輸入。 該文件如下所示:
----------------------------------------------------------------
Hi Then Finish
End Okay
----------------------------------------------------------------
Here is the layout for it:
Character Set 1: 1-6
Character Set 2: 7 (always a space)
Character Set 3: 8-11
Character Set 4: 12-13 (always 2 spaces)
Character Set 5: 14-19
我想知道是否有一種方法來獲取字符串中一定數量的字符。 每個字符集也將具有不同的變量。
例如:字符集1將被稱為label ,字符集3將被稱為code ,字符集5將被稱為operation 。
我嘗試了類似的東西
for (int i = 0; !text.eof(); i++){
getline(text, label[i]);
getline(text, code[i]);
getline(text, operation[i]);
}
如果有幫助的話,現在這是我的代碼...即使它不能正常工作:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
const int MAX = 100;
string str;
string symLabel[MAX];
string opCode [MAX];
string operand [MAX];
ifstream sim("simprog.txt");
for (int i = 0; !sim.eof(); i++){
getline(sim, str);
symLabel[i] = str.substr(0, 6);
opCode[i] = str.substr(8,11);
operand[i] = str.substr(13, 18);
cout << symLabel[i] << endl;
cout << opCode[i] << endl;
}
}
我將數組更改為rec的向量,其中rec是添加復制構造函數和operator =的字符串結構,以使其與STL容器兼容。 這不會將您限制為特定數量的輸入行。 剩下的只是對代碼的一些更改。
struct rec
{
rec() { }
rec(const rec &r) { *this = r; }
rec &operator=(const rec &r)
{
if (this != &r)
{
symLabel = r.symLabel;
opCode = r.opCode;
operand = r.operand;
}
return *this;
}
std::string symLabel;
std::string opCode;
std::string operand;
};
int main(int argc, char *argv[])
{
std::string str;
std::vector<rec> records;
std::ifstream sim("simprog.txt");
char bf[100];
while(sim.good())
{
sim.getline(bf, sizeof(bf));
str = bf;
rec r;
r.symLabel = str.substr(0, 6);
r.opCode = str.substr(7, 5);
r.operand = str.substr(13, 6);
records.push_back(r);
}
for (size_t i=0; i< records.size(); i++)
{
std::cout << records[i].symLabel << std::endl;
std::cout << records[i].opCode << std::endl;
}
return 0;
}
請注意,這需要您指定的格式正確的文件。 如果行格式更改,或最后一行不完整,您將遇到麻煩:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.