Hi!
To get some practice in C++ (and work towards the problem I am going to use C++ for), I wrote a program that would translate strings, that contain digits, to integers. To do so I:
1. Scale down the value of the characters, so that thay correspond to digits 0 - 9 of type int (from string to vector)
2. add up the items in the vector so that they become one single integer.
All seems to be working well, but for a bunch of values that are miraculously generated outside the domain of the vector. The fragment of the code, where it seems to go wrong:
Code:
vector<int> Dscale (const string& Txt) { // translates digits in a text string to digits in a vector
vector<int> Dig(0);
int n = -1;
while (Txt[++n]) {
Dig.push_back((Txt[n])-48);
cout << "Dscale: " << Txt[n] - 48 << endl;
}
cout << "Txt size " << Txt.size() << " and Dig size " << Dig.size() << endl;
Dig.resize(Txt.size());
cout << "Txt size " << Txt.size() << " and Dig size " << Dig.size() << endl;
n = -1;
while (Dig[++n]) {
cout << "Dscale vector item " << n << " has value " << Dig[n] << endl;
}
return Dig;
}
I added the cout, so I could see what happens, for the input 1234 (in Txt), the output is:
Code:
Dscale: 1
Dscale: 2
Dscale: 3
Dscale: 4
Txt size 4 and Dig size 4
Txt size 4 and Dig size 4
Dscale vector item 0 has value 1
Dscale vector item 1 has value 2
Dscale vector item 2 has value 3
Dscale vector item 3 has value 4
Dscale vector item 4 has value 196715
Dscale vector item 5 has value 4096
Dscale vector item 6 has value 4064464
Dscale vector item 7 has value 4064464
In short, so you don't have to waste time to figure out the meaning from the code:
- the Dscale series, gives the values in the string Txt
- the next two rows give the lengths of both string Txt and vector Dig
- the Descale vector series, gives the values in the vector Dig
The last being produced in the condition: while (Dig[++n])
The reading of Dig is restricted to the first four items for: while (n++ < series.size())
so it needn't be a problem (and the program in total is working as it should). I'm simply very curious where the other items come from. Especially because the vector is declared empty (vector<int> Dig(0).
Cheers, Carola