Hey guys, I was wondering if you could help me out with this problem on my program. I ask the user to guess a letter. If the letter is not found in the string , i tell them that it's wrong. But that does not work the program stops and gives me a "debug assertion failed " error. Can somebody tell me how to fix this.
for ( i = 0; i < name.length(); i++ )
store[i] = name[i];
if ( letter != name[i] )
Why would this not work? Try printing the number 'i' in your if statement and see what value you get. Remember that string is just an array of characters and the first character starts at index 0. So the first character in name is name = 'h'
How about just setting a boolean if the letter is found?
Your problem in the original code is what Smac89 pointed out, you're trying to index past the region of code your string is allowed to access. Remember that the for loop will increment i once "after" it aborts. (It actually increments before and then aborts immediately because the condition is false)
Also, why are you using an array of strings to store single characters from the "secret word"?
Then again, why do you need to store the characters separately in the first case? You never use them afterwards.
And the test to see if the letter exists in the word isn't correct. You're only checking against the last character in the word.
I'd write a function that returns true or false based on if a letter is in a word you pass it. It'll modularize it nicely, you can just return a boolean to let you know if the letter is in the word or not.
To tackle the loop, if you create a function you can actually use hoity's code and modify it slightly to return true or false instead of 0 and printing "wrong".
#include <string>//string class
#include <fstream>//file I/O
string name="hello";//You have a string
string store;//You allocated storage space for a 2-Dimensional array of strings
//i.e. string within a string
int main ()
cout<<"enter a letter : ";//Prompt for a letter
cin>>letter;//User enters letter
for ( i = 0; i < name.length(); i++ )//For loop
store[i] = name[i];//The top part of the 2d array store the character in name
//So store = 'h', store = 'e', store = 'l'...etc
//At this point, i is 5
if ( letter != name[i] )//check that letter is equal to name
//name = null terminating character. It is the character at the end of every string
//that signifies to the computer that that is the end of the string. It looks like this '\0'
cout<<"wrong"<<endl;//After checking that letter is not equal to null terminating character,
//you print out the message "wrong"
return 0;//return success
Notice that no where in your code did you compare the letter you received to the letters in the string 'name'. You only checked it against a null terminating character and that is why you will always get the same message unless you do something different