CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2009
    Posts
    6

    Comparing an inputted char to a string

    I am currently working on a hangman game right now and I need to be able to compare an inputted char to the sting containing the current word for the game. but I don't know how to do that!

    Here is what I have so far. I word to guess is "programming" and is extracted from a separate .dat file.

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <cctype>

    using namespace std;

    const string blank;

    int main()
    {
    ifstream inFile;
    ofstream outFile;

    string wordToGuess;

    char guessLetter;

    inFile.open("hangman.dat");

    cout << "Word: computer\n"
    << "Word: science\n"
    << "Word: programming\n\n";

    inFile >> wordToGuess >> wordToGuess >> wordToGuess;

    cout << "First Word in File to Guess: " << wordToGuess << endl << endl;

    cout << " -------|\n",
    cout << " | |\n",
    cout << " |\n",
    cout << " |\n",
    cout << " |\n",
    cout << " |\n",
    cout << " -----";


    cout << "\n\nEnter a letter to guess: ";



    cin >> guessLetter;


    guessLetter = toupper(guessLetter);

    cout << "You entered: " << guessLetter << endl << endl;

    cout << endl << endl;

    (here is where I need to check "guessLetter" to "wordToGuess" which is the string "programming")

    [/code]

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Comparing an inputted char to a string

    Quote Originally Posted by Shadoninja View Post
    I am currently working on a hangman game right now and I need to be able to compare an inputted char to the sting containing the current word for the game. but I don't know how to do that!
    1) Write a loop testing each character in the string to the inputted character

    or

    2) Use std::find to search a series of value for a particular value.
    Code:
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        string s = "abc123";
    
       // search for the letter 'c' in string s
        if ( find( s.begin(), s.end(), 'c') != s.end())
       {
           // the letter 'c' exists in abc123
       }
       else
       {
            // letter 'c' does not exist
       }
    }
    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Jul 2009
    Posts
    6

    Re: Comparing an inputted char to a string

    Thank you!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured