Why gets() function isn't working here? cin.getline() doesn't work either | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why gets() function isn't working here? cin.getline() doesn't work either

#include<iostream> #include<cstring> using namespace std; int main() { char string1[50]; char string2[50]; int l; int l1; int l2; int n; cin >> n; while (n) { gets(string1); gets(string2); l1 = strlen(string1); l2 = strlen(string2); if (l1 <= l2) l = l2; else l = l1; for (int i = 0; i < l; i++) { if (i < l1) cout << string1[i]; if (i < l2) cout << string2[i]; } cout << endl; n--; } }

23rd Sep 2020, 3:28 PM
Mohammed Joy
Mohammed Joy - avatar
5 Answers
+ 3
You can read why gets risky https://www.google.com/amp/s/www.geeksforgeeks.org/gets-is-risky-to-use/amp/ You did one another mistake in your program when you comparing both String if u comparing two string with equal (==) sign this is completely invalid in c or cpp use can use strcmp(). function .
23rd Sep 2020, 3:53 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 3
Are getline funtion only for c++? If yes then what can I use in c to take a string with a gap?
23rd Sep 2020, 4:12 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 3
Thanks Arsenic for your help.
23rd Sep 2020, 4:21 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 2
Samsil Arefeen there are a lot of ways to do so 1) using the classic istream::getline() function instead of the new C++ version of the same {http://www.cplusplus.com/reference/istream/istream/getline/} 2) using fgets() function {https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm} 3) using the good old scanf() function like this 👇 scanf("%[^\t\n]",string)
23rd Sep 2020, 4:19 PM
Arsenic
Arsenic - avatar
+ 1
gets() is not working as it has been removed from the standards a while ago due to its dangerous behaviour of overflowing buffer. cin.getline() function required <string> header to be included in you program
23rd Sep 2020, 3:44 PM
Arsenic
Arsenic - avatar