Reputation: 71
I need to read only numbers from a file. The file contains:
0
#####################
# | | | #
# | | | 2#
# | | 2| #
# | | | #
#####################
I only want to read the first 0 that will be the score and the other two numbers. Whitespaces I want to save them as 0. I want to save the score into an int and the rest into a vector.
So the vector should contain:
score = 0
0000000200200000
My code is the next, but it doesn't work:
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();
}
And here is the str2int function
int str2int(string s){
istringstream reader(s);
unsigned int val = 0;
reader >> val;
return val;
}
Thank you very much.
Upvotes: 0
Views: 1611
Reputation: 126
Just ignore the other input and save what is a digit , check what i did it worked for the same text file you posted, in the end the vector must have 0 2 2 as values. screenshot
I forgot to make 0 all the other characters but that isn't an issue now just replace continue; statement in the screen shot with nums.push_back(0);
Upvotes: 0
Reputation: 19607
I would use only simple stream extraction operations here (actually, maybe boost::regex_split
), no std::string
parsing.
Read the first 0
with operator>>
, then std::ignore
to remove the trailing newline character, or std::getline
and check if no extra (non-whitespace) characters are present
std::ignore
or std::getline
and validate the ####
lines.
Use operator>>
with a char
and validate that it is #
.
In a loop, try operator>>
with int
defaulted to 0
, if it fails, in.clear()
and use operator>>
with a char
to read what doesn't seem to be a number, but either |
or #
. Continue the loop according to that.
Handle the rest of the line after the second #
similarly to the 1st bullet point
Always check if every extraction operation succeeded.
Upvotes: 1