• home
  • forum
  • my
  • kt
  • download
  • Taking User Input Containing Spaces

    Author: 2009-03-17 08:49:50 From:

    In c++, many a times, you’d want to take a string as an input. But the default cin statement cannot accept spaces, i.e. it terminates the input when it encounters a space. For eg, if you input ‘Hello World’, only ‘Hello’ would be stored and rest all discarded. To overcome this, we have a function called cin.getline().

    view plaincopy to clipboardprint?
    1. #include <iostream>   
    2.   
    3. using namespace std;   
    4.   
    5. int main()   
    6. {   
    7.     char stn[20];   
    8.     cin.getline(stn,20);   
    9.     cout<<stn;   
    10.     system("PAUSE");   
    11.     return 0;   
    12. }  

    The cin.getline() function accepts two parameters, one is the variable where the input would be stored, and second is the maximum input length.

    Lets dissect the above code,

    • First, we declare a variable stn to store a string of maximum length 20.
    • We use the cin.getline() function, with the first parameter as our declared variable stn and second parameter as the maximum length that stn can hold, i.e 20.
    • Remember, for example if you specify the length as 5, only a maximum of 4 characters would be taken as input from the user, even if he exceeds this limit. This is because the 5th place is used to store the null terminator.

    Thus, the function is quite similar to the standard cin function, only that it even allows for spaces.

    Have any suggestions or anything to say? Write a comment below!

    discuss this topic to forum

    relation tutorial

    No information

    Category

      Database Related (0)
      Development (5)
      File Manipulation (3)
      Games and Entertainment (10)
      Graphics (15)
      Introduction to C and Cpp (24)
      Miscellaneous (9)
      Networking (5)
      Programming in C and Cpp (10)
      Security (3)

    New

    Hot