For this program I am trying to make first ask for the users name, print this as a lowercase, and then make a menu, and then for option 1 the program asks the user to guess a random number between 1-100. When I try to run the below code, the error I get is:
program.cpp:51:11: error: 'name' was not declared in this scope; did you mean 'tzname'? 51 | cin>>name; | ^~~~ | tzname
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "splashkit.h"
#include <string>
using namespace std;
void play_game()
{
int random = rand() % 101; //has to be 101 as when it divides it will be between 1-100
std::cout << random << std::endl;
std::cout << "Guess a number: ";
while(true)
{
int guess;
std::cin >> guess;
if(guess == random)
{
std::cout << "You win!\n";
break; //stops program if guessed right, otherwise keep going
}
else if (guess < random)
{
std::cout << "Too low\n";
}
else if (guess > random)
{
std::cout << "Too high\n";
}
}
}
void toSmall(char * name) //function to convert characters to lower case
{
int i=0;
while(name[i]!= '\0'){
if(name[i]>=65 && name[i]<=90){
name[i]= name[i] 32;
}
i ;
}
}
int main()
{
srand(time(NULL)); //to stop same sequence appearing everytime, seeds a random number each
time
cout<<"\nEnter your name: ";
cin>>name;
toSmall(name) ; //converts all character to lowercase
cout<<"Welcome To the Game: \n"<<name;
int choice;
do
{
std::cout << "0. Quit" << std::endl << "1. Play Game\n";
std::cin >> choice;
switch(choice)
{
case 0:
std::cout << "Game quit\n";
return 0;
case 1:
play_game();
break;
}
}
while(choice != 0);
}
CodePudding user response:
What is wrong with my code? I get an error saying I have no declared 'name'
The problem is that there is no variable named name
inside main()
. That is, you're trying to read into name
using cin>>name;
when there is no variable called name
that can be used here.
To solve this you can create a variable called name
of type say std::string
before trying to read into it:
std::string name;
std::cin >> name;
Note also that you can then pass name
to toSmall
by changing its declaration to
//-----------------------v------->pass by reference
void toSmall(std::string &pname)
{
//code here
}
You can also use std::to_lower
if you're allowed to use library function instead of writing one yourself.