+ 1

using cin with char* variables

When trying to use cin with char*, as below, the code does not produce any result: ... char* word; cin >> word; cout << word; ... What is the right way to get user input for char* type variable?

30th Aug 2016, 10:16 PM
Turgai Shikhlinski
Turgai Shikhlinski - avatar
6 odpowiedzi
+ 3
You forgot the memory allocation. char* word = new char[20]; cin >> word; cout << word;
30th Aug 2016, 10:42 PM
Zen
Zen - avatar
+ 2
Pls guys, do not read input into a limited buffer without making sure the buffer limit is not exceeded by the read. Don't make any assumptions what you will get as an input. The input in your example could be arbitrary code of arbitrary length... that might be garbage or binary code that an attacker will later try to get executed... This is an example for code injection.
30th Aug 2016, 11:12 PM
Stefan
Stefan - avatar
0
Code playground says: No output
30th Aug 2016, 10:31 PM
Turgai Shikhlinski
Turgai Shikhlinski - avatar
0
Shrek is love
31st Aug 2016, 2:01 AM
nic
0
@Zen, thanks for the answer, it works! I also tried it with string operator and found this solution: string word; getline(cin,word); cout<<word
31st Aug 2016, 6:07 AM
Turgai Shikhlinski
Turgai Shikhlinski - avatar
0
@Stefan, do you mean we should always limit input length when using strings?
31st Aug 2016, 6:09 AM
Turgai Shikhlinski
Turgai Shikhlinski - avatar