Beginner std::cin question/problem.

In the code below the first thing the program will do is ask the user their Username. I have an IF statement just after that to determine if the user has left it blank, and if so to have it exit the program, otherwise jumps to another function. The problem is that when I test it and dont enter any user data, then hit enter, it just jumps the cursor to the next line, and will skip a line each time I hit enter. For learning/testing purposes I want it to just exit when they type no name and hit enter, instead of just jumping down a line until they finally do enter something, and press enter. Thanks folks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 #include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string>

int guessNumber();

std::string name;

int getName()
{
	std::cout << "Please enter your Username: ";
	std::cin >> name;

	if (name != "")
	{
		guessNumber();
	}
	else
	{
		exit;
	}

	return 0;
}

int guessNumber()
{
	return 0;
}

int playAgain()
{
	return 0;
}

int main()
{
	getName();
	guessNumber();
	playAgain();

	return 0;
}
http://www.cplusplus.com/reference/istream/ws/
use http://www.cplusplus.com/reference/string/string/getline/


Also, you forgot the parenthesis in line 21 exit();


PS: ¿why does `getName()' calls `guessNumber()'
Last edited on
Because once the function getName has finished it's task of "getting the users name" I want it to move onto guessNumber where I'll have the code for the actual number guessing game. Is this not good practice? Should my program not be broken up into separate functions to handle separate tasks instead of cramming it all into the main function?

EDIT: I guess it doesnt need to call guessNumber as it's already assigned to in the main function, right?
Last edited on
Also I'm not understanding the getline functionality. Could you give me an example of how to apply this to my code?
"getline" retrieves the entire line of input until a newline character is reached (it does not skip whitespace like "cin" does).

1
2
string myString;
getline(cin, myString);


If the user enters multiple words, this will capture all of them. If you want to do something based on what the user entered, you will have to parse this string and break it up.
Alright got it. I've managed to fix my issues using getline and length() to verify a username minimum lengths. Thanks folks!
> I guess it doesnt need to call guessNumber as it's already assigned to in the main function, right?
¿assigned?

> once the function getName has finished it's task of "getting the users name"
> I want it to move onto guessNumber
1
2
	getName(); //once this function finish;
	guessNumber(); //this one would be executed (automagically) 
It is not a responsibility of `getName()' to call the next function, for all that it care, it is alone in the world.
Topic archived. No new replies allowed.