String Subscript out of Range
Oct 16, 2014 at 9:17pm UTC
Hey there. I'm fairly new to C++ and I've encountered an error that I'm not certain how to solve. The aim of the program is for the user to input a 4 digit number and for the computer to try and guess it.
The error states: "String Subscript out of Range"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include <iostream>
#include <random>
#include <string>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::to_string;
std::default_random_engine generator;
std::uniform_int_distribution<int > distribution(0, 9);
string attempt(string ans, string prevGuess) {
string a, b, c, d;
if (prevGuess[0] != ans[0])
string a = to_string(distribution(generator));
else
string a = to_string(prevGuess[0]);
if (prevGuess[1] != ans[1])
string b = to_string(distribution(generator));
else
string b = to_string(prevGuess[1]);
if (prevGuess[2] != ans[2])
string c = to_string(distribution(generator));
else
string c = to_string(prevGuess[2]);
if (prevGuess[3] != ans[3])
string d = to_string(distribution(generator));
else
string d = to_string(prevGuess[3]);
string atmp = a + b + c + d;
return atmp;
}
int main() {
cout << "Please enter a 4 digit number: " ;
int number;
cin >> number;
if (to_string(number).length() != 4) {
cout << "Invalid Number!" ;
return -1;
}
cout << "\n" ;
string guess = attempt(to_string(number), to_string(1111));
int counter = 1;
while (guess != to_string(number)) {
cout << "Guess " << to_string(counter) << ": " << guess;
++counter;
guess = attempt(to_string(number), guess);
}
cout << "The computer guessed " << to_string(number) << "in " << to_string(counter) << " guesses!\n" ;
return 0;
}
Any help on this would be very much appreciated. Again, many apologies as I am still fairly new to C++. Thanks in advance.
Oct 16, 2014 at 9:28pm UTC
How long is atmp?
If not 4, then how long are a, b, c, d?
Lines 17, 22, 27, and 32. You call to_string. Why?
Oct 16, 2014 at 9:34pm UTC
atmp should be 4 characters long and as for the to_string, I thought that the absence of a to_string may have caused the problem, so I added them.
Oct 16, 2014 at 10:54pm UTC
No "should be". Make your program show the true length. That is one method of debugging.
prevGuess[x] is a
char
. to_string does not take a char. There must occur implicit conversion (to int?).
Now consider this:
1 2 3 4 5 6 7 8 9 10 11 12
string attempt(string ans, string prevGuess) {
if ( ans.size() == prevGuess.size() ) {
for ( size_t pos = 0; pos < prevGuess.size(); ++pos ) {
if ( prevGuess[pos] != ans[pos] ) {
string guess { to_string(distribution(generator)) };
if ( 1 == guess.size() ) prevGuess[pos] = guess[0]; // update mismatching position
else cout << "size error (" << guess << ")\n" ;
}
}
}
return prevGuess;
}
Topic archived. No new replies allowed.