1

Basically I need user input for an integer, I tried these methods:

#include <iostream>
int main() {
 int PID;
 scanf("%i",&PID); //attempt 0
 cin >> PID; //attempt 1
}

any ideas?

  • What's your question? – zdd Mar 07 '14 at 01:55
  • http://stackoverflow.com/questions/7944861/getting-user-input-in-c – Andy_A̷n̷d̷y̷ Mar 07 '14 at 01:56
  • 1
    `_getch();` in visual studio. Warning this is **deprecated** and NOT recommended (`conio.h`) – yizzlez Mar 07 '14 at 02:01
  • C input streams are defined as being line-buffered, so you might not see any input until a newline has been sent. If you want to read characters without the user pressing Enter you will have to use operating system-specific commands instead of Standard C. Maybe look at the `ncurses` library. – M.M Mar 07 '14 at 03:15

1 Answers1

3

Most command-line input methods require the user to press ENTER to signal the end of the input, even if the app does not use the line break.

If you do not want the user to end the input with ENTER then you will likely have to resort to reading the input 1 character at a time and handle data conversions manually. The problem is, without a line break, how do you know when the user has finished typing the input? When the user has typed X number of characters/digits? What if the user types fewer then your max? Start a timer and stop reading when the user stops typing for X seconds? See the problem?

Line breaks are not something to be ignored. You should re-design your input logic to accept them, not avoid them. If that is really not an option, then maybe you need to re-think why you are creating a command-line app in the first place instead of a GUI app where the user can press a button when ready.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I am afraid I cannot change the way my program works, because an integer is required for a PID and a newline is not helpful. Perhaps there is a way I can remove the newline? eg. foo.remove("\n"); – user3081016 Mar 07 '14 at 06:27
  • You can use `cin >> PID` to read the integer, and then use `cin.ignore(numeric_limits::max(), '\n')` to ignore any subsequent input after the integer up to and including the line break. See http://stackoverflow.com/questions/5131647/ – Remy Lebeau Mar 07 '14 at 18:59