Hey everyone! I'm going to turn 15 next month and I wanted to have a career in game development. I've started programming just yesterday evening so I'm a complete noob at everything haha XD anyways I made a simple program, a sort of game where you have to guess a random number the computer generates. At the start I added a simple "Hello, what's your name?" where name would be the value assigned to a string variable. The problem is, when I type in something with a space in it, the program just shuts down. Please explain to me why! I think it has something to do with the while loop. Thanks :)
IN SHORT : Whenever I type in a name with a space (example: Ellie Goulding) my program just shuts down.
#include <iostream>
#include <cmath>
#include <ctime>
#include <string>
#include <Windows.h>
usingnamespace std;
int main()
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int num, numrand;
char yn;
string name;
srand(time(NULL));
SetConsoleTextAttribute(h, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
cout << "Hello there! What is your name? "; // Computer asks you for your name
cin >> name;
while (true) // This loop is here so the player has to type either "n" or "y"
{
cout << "Hello there, " << name << " ! Would you like to play a game? (y/n)" << endl;
cin >> yn;
if (yn == 'n' || yn == 'N')
{
return 0;
}
if (yn == 'y' || yn == 'Y')
{
break;
}
}
while (true) // This loop will repeat the game until the player guesses the number
{
if (yn == 'y' || yn == 'Y')
{
cout << "The computer is going to generate a random number between 0 and 10. You have to guess it!" << endl;
cout << "Guess the number!" << endl;
numrand = (rand() % 11);
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
cin >> num;
if (num == numrand)
{
cout << "You win!" << endl;
break;
}
if (num != numrand)
{
SetConsoleTextAttribute(h, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
cout << "Wrong! The computer guessed " << numrand << " . Try again!" << endl;
}
}
}
system("pause");
return 0;
}
Thanks! I can't understand how to use it properly, though. Instead of std::cin, I have to use std::getline, but what do the values in the () mean? Like, does it mean "Save in memory what the user types (getline) as an input (cin) and store that memory into my string (name)? Not so sure. Please explain if you could. Thanks! :)
getline takes two parameters: an istream object and a std::string object (there is also an overload that allows you specify a delimiting character, but disregard that for now). The contract of getline basically tells you "Give me an input stream, and give me a string. I will read a line out of the input stream and put it in the string you give me." As a programmer, when you say std::getline (std::cin,name); you are taking advantage of that contract. You're saying "Ok, getline, the input stream I want you to read from is called cin. Read from there and stick the data in this string I have called name."