简体   繁体   中英

C++ letter guessing game

I'm creating a guessing game with the input being parsed through the command line argument. I've managed to replace all the words with '*'. I have to get input from the user to guess a letter and decrypt the message. I am having problems in terms of replacing the letters back and I have no idea on how to start. Appreciate some assistance from you guys.

using namespace std;

int main(int argc,char *argv[])
{
char letter;
string s(argv[1]);
string s2(argv[2]);
string s3(argv[3]);


  if(argc == 1)
  {
     cout<<"No arguments.You should run this program in terminal with an argument."<<endl;
     exit(1);
  }
   else
   { 
    if (s.find("programming") != string::npos)
    s.replace(s.find("programming"), 11, "***********");
    if (s2.find("is") != string::npos)
    s2.replace(s2.find("is"), 2, "**");
    if (s3.find("awesome") != string::npos)
    s3.replace(s3.find("awesome"), 7, "*******");

    cout<<"Guess a letter in the message: " << s <<" "<< s2 <<" "<< s3 <<endl;
    cout<<"Enter a letter to guess: ";

    cin>>letter;

  }
  return 0;
}

Ok. I'll try to help you somehow...

First. you launch program assuming, that you passed 3 strings as an argument to the program and you are assigning it to the std::string variables. Then you are checking, wheather you passed those 3 arguments.

That is wrong. What if you do not pass 3 arguments and launch a program? What will be held in argv[1] argv[2] and argv[3]? Some rubbish nothing more and if you are lucky enough your program won't crash. You should first check wheather you passed arguments and if so then make any assignments associated with them. Otherwise you are assigning rubbish to s , s2 and s3

If you want to continously check for input arguments. You should use do...while() loop. I won't describe it here as it can be found anywhere on the Internet. Everytime you simply check if given letter is in any of the strings "programming" , "is" , "awesome" and then replace your **** on correct position with a given letter if letter is found. You should do this while(any of the strings has a letter '*' in it).

That's how I would describe the problem, but I won't write this for you. It's best to learn, when you programm.

I would ask you to make more effort before asking on this forum. you should at least try to use any while loop to accomplish your task and not give this to us. Hovewer I understand, that someone has to start somewhere and beginnings are not easy. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM