cin.get() vs cin.getline() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

cin.get() vs cin.getline()

why SL compiler doesn't recognizes cin.get() whereas cin.getline() works well? while using cin.get() it doesn't even show me any errors and neither it works on other compilers it works fine. I am attaching two codes for this problem https://code.sololearn.com/c5ixK3hD5LMj/?ref=app https://code.sololearn.com/cl61LJNclmMp/?ref=app

2nd Jan 2018, 12:32 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
8 Answers
+ 14
Code Playground doesn't recognize that std::cin.get() should prompt for user input when the input stream is empty. However, this doesn't necessarily mean that the function does not work on SL. This is the interesting part. As a workaround, it is possible to write to the input stream, and then extract from the input stream using std::cin.get(). Try doing: std::cin >> std::ws; std::cin.get(arr, 10); This will get user input, store it into the input stream, remove leading whitespaces, and then get() will extract 10 characters from the input stream, store it into arr. To modify your code: #include <iostream> using namespace std; int main() { char str1[40]; cin>>ws; cin.get(str1,40); cout << string(str1); return 0; }
2nd Jan 2018, 1:34 PM
Hatsy Rei
Hatsy Rei - avatar
+ 9
@Saurabh It is just one of the ways to write to the input stream, which can then be extracted later.
2nd Jan 2018, 2:10 PM
Hatsy Rei
Hatsy Rei - avatar
+ 9
@Saurabh Yes, but there are times when you will want to use it, e.g. input validation before extracting from the input stream and placing it into a variable. It is not a requirement, it is knowing what you can do with it.
2nd Jan 2018, 2:17 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
It seems that code playground has not included cin.get() in the list of functions to get input. But if you place a dummy cin>> in the code, the buffer can read input and then cin.get() can use the same input for the array. So add this line in your code: #define _ cin>>
2nd Jan 2018, 1:35 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 5
I had some spaces in between the command. You cannot ignore those.
2nd Jan 2018, 2:09 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 4
thnx for ur help @hatsy!!!!
2nd Jan 2018, 2:19 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 3
@kinshuk yep I got it!! thnx again! @hatsy most of the compilers doesn't require that thing
2nd Jan 2018, 2:14 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 2
thnx both of us @hatsy and @kinshuk kinshuk I tried #define_cin>> but it shows an error and @hatsy can u explain me why cin>>ws is required while using cin.get()
2nd Jan 2018, 2:08 PM
Saurabh Tiwari
Saurabh Tiwari - avatar