std::cin input being skipped?

Some input is being skipped and it sets the variable to null or empty or something. Here is the relevant code
1
2
3
4
5
6
7
8
9
10
11
12
13
short int bindedPort;

//prompt for the port
std::cout<<"What port would you like to bind to?"<<std::flush;
std::cin >> bindedPort;
std::cout << std::endl;

 std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

// Let the server know this client is connected
std::string ID;
std::cout<<"\nEnter an ID: "<<std::flush;
ID = std::cin.get();


The first cin works but the second one is skipped and an empty string is sent to the server. Can someone help me?
Try
std::cin.get(ID);
or
std::getline(cin, ID);
Neither of those were valid lines of code. :/
Depends on the definition of ID.

http://www.cplusplus.com/reference/istream/istream/get/
1
2
    char ID[10];
    std::cin.get(ID,10);


http://www.cplusplus.com/reference/string/getline/
1
2
    std::string ID;
    std::getline(cin, ID);


I've created a new empty project and filled it with this code. It still skips the second input though.

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
#include <iostream>
#include <string>

using namespace std;



int main()
{

   short bindedPort;
   //prompt for the port
   std::cout<<"What port would you like to bind to?"<<std::flush;
   std::cin >> bindedPort;
   std::cout << std::endl;

   //std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

   // Let the server know this client is connected
   std::string ID;
   std::cout<<"\nEnter an ID: "<<std::flush;
   std::getline(cin, ID);


   return(0);
}
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
#include <iostream>
#include <string>

using namespace std;



int main()
{

   short bindedPort;
   //prompt for the port
   std::cout<<"What port would you like to bind to?"<<std::flush;
   std::cin >> bindedPort;
   std::cout << std::endl;

   //std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

   // Let the server know this client is connected
   std::string ID;
   std::cout<<"\nEnter an ID: "<<std::flush;
   cin.get();     //changed
   std::getline(cin, ID);

   system("pause");
   return(0);
}


Is this what you wanted? Also I have a question why do you have using namespace std; but you are typing std before everything?
The '\n' newline character is still in the buffer from the first cin statement.

Use either std::cin.sync(); or reinstate the cin.ignore which is currently commented out, to clear the buffer before the getline().

http://www.cplusplus.com/reference/istream/istream/sync/
Topic archived. No new replies allowed.