[英]How to read only numbers in file .txt?
我只需要讀取文件中的數字。 該文件包含:
0
#####################
# | | | #
# | | | 2#
# | | 2| #
# | | | #
#####################
我只想讀取第一個0,即比分,另兩個數字。 空格我想將它們保存為0。我想將比分保存為一個整型,其余為一個矢量。
因此向量應包含:
score = 0
0000000200200000
我的代碼是下一個,但是不起作用:
string line;
vector<int> v;
int sscore = 0, count = 0;
ifstream in ("save_game.txt");
vector<vector<Tile> > vt;
if (in.is_open()) {
while (getline (in, line)) {
if (line.size() == 1)
sscore = str2int(line);
else {
for (int i = 0; i < (int) line.size(); i++) {
string l = line.substr(i, 1);
char c = l[0];
if (l[0] == '#' || l[0] == '|') {count = 0;}
else {
if (c != ' ') {
count = 0;
int ss = str2int(l);
v.push_back(ss);
}
else {
count++;
if (count == 3)
v.push_back(0);
}
}
}
}
}
in.close();
}
這是str2int函數
int str2int(string s){
istringstream reader(s);
unsigned int val = 0;
reader >> val;
return val;
}
非常感謝你。
我在這里只使用簡單的流提取操作(實際上,也許是boost::regex_split
),而沒有std::string
解析。
使用operator>>
讀取第一個0
,然后讀取std::ignore
以刪除結尾的換行符,或讀取std::getline
並檢查是否不存在多余的(非空白)字符
std::ignore
或std::getline
並驗證####
行。
將operator>>
與char
一起使用,並驗證其為#
。
在循環中,嘗試將int
缺省設置為0
operator>>
,如果失敗, in.clear()
使用in.clear()
並將operator>>
與char
一起使用以讀取似乎不是數字的值,但是|
或#
。 根據此繼續循環。
處理行的其余部分之后的第二#
類似於第一個圓點
始終檢查每個提取操作是否成功。
只需忽略其他輸入並保存數字,檢查我對您發布的同一文本文件所做的工作,最后向量必須具有0 2 2作為值。 屏幕截圖
我忘了將所有其他字符設為0,但這不是問題,只需替換continue; 屏幕截圖中的nums.push_back(0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.