User input to string class based strings – CSKC
Sign In

Search

Code Learning #CPP#3023    siteicon   siteicon  

User input to string class based strings

Collecting user input to string class string objects using cin and getline()

Learning Objectives

  • Learning to collect whole sentences into the string class based objects.
  • Learning why cin fails and getline(cin,<string object>) works.

Source Code

TC++ #3023

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

Code Understanding

string s; //object s of string class declared

cout<<“Enter a sentence : “;Β cin>>s;
Collecting a sentence into string object using cin. It will collect first word only due to limitation of cin

cout<<s<<endl; //This will print the first word only of given sentence

cin.ignore(250,’n’);
This will help to ignore the last newline (n) entered after the cin input so that next getline function can operate well. Without this you won’t be able to collect next input. 250 is an arbitray long value assuming that previously given cin input is less than 250 chars.

cout<<“Enter another sentence : “;Β  //Prompt for next sentence

getline(cin,s);
This will collect the whole sentence from the console and put it into the s the string class object declared earlier.

cout<<s<<endl;
This will print the newly updated value of s.

 

Notes

  • getline(cin,<string object> of string class is different from cin.getline(<char array>,<size>) used for null terminated string. The getline method of string class doesn’t need any size parameter as it can collect an arbitrarily long string.
  • cin.ignore needs to be carfully used for ignoring long range of white spaces after the expected input. The ideal method of cin.ignore is as follows.
    cin.ignore(std::numeric_limits<std::streamsize>::max(), β€˜n’);
    We have not given it here as it is too verbose and is difficult to comprehend for many students.

Common Errors

  • Student often confuse between cin.getline(<char array>,<size>) and getline(cin,<string object>) regarding where what is used. The best way to remember is that one with string class doesn’t need a size parameter.


Suggested Filename(s): strclip.cpp



Share

Created: 25-Jan-2018 23:25 | Updated: 25-Jan-2018 23:39|