void messaging()
{
while(true)
{
std::cout << "Enter message: ";
char message[128];
std::cin.getline(message,128);
}
}
int main()
{
unsigned port;
std::string localhost;
std::cout << "Enter port you want to connect to: ";
std::cin >> port;
std::cout << "Enter address or name of host: ";
std::cin >> localhost;
if ( socket.connect(localhost,port) == 0 )
{
std::cout << "Enter your name: ";
char name[128];
std::cin.getline(name,128);
}
sf::Thread thread(&messaging)
thread.launch();
}
so in this first snippet
Enter port you want to connect to: 5000
Enter the address or name of host: 192.168.1.102
Enter your name: Enter message: // see? it doesnt block the program, it should wait until the user type a name
but when i do this i dont get any problem, the getline blocks the program
works perfectly
On line 16 you ask the user to enter an ip address. So lets assume the user enters 192.168.1.102. However, the user will also press enter at the end of 192.168.1.102. So the input actually looks like this 192.168.1.102\n. Note the newline at the end.
On line 17 the statement std::cin >> localhost; is executed. The >> operator stops reading when it encounters whitespace. The newline character is considered whitespace. So this statement std::cin >> localhost; reads in 192.168.1.102. This leaves behind a newline character.
On line 23 you call getline std::cin.getline(name,128); which reads until it encounters a newline character, but remember the previous operation left a newline in the input stream, so the first character getline encounters is a newline. So the newline is extracted from the stream but nothing is placed in you name variable.
Okay, that was a very good explanation, how about the 2nd snippet? When i put my name and then enter it should skip the first
enter a message:
Because newline will left from when i input the name. But that doesnt happen? I just want tp understand. Base from your explanation the output in the 2nd snippet should be
Enter your name: myname
Enter message: Enter message:
The getline function does not leave a newline in the input stream. Only the >> operator does that. The getline function reads up to its delimiter. Witch by default is the newline character. The delimiter is extracted from the stream and discarded, so no newline is left behind.
This is only a problem when you have a statement such as std::cin >> var; followed by a getline statement e.g.
1 2
std::cin >> var;
std::getline(std::cin, port);
In this example
1 2 3 4
std::cout << "Enter port you want to connect to: ";
std::cin >> port;
std::cout << "Enter address or name of host: ";
std::cin >> localhost;
Lets assume the user enters 80 in response to the first std::cout statement. As discussed before a newline is also entered so the input looks like this 80\n.
On line 2 the 80 is extracted leaving a newline behind.
The >> operator however, skips over leading whitespace. So on line 4 the newline left behind on line 2 is simply ignored.