0

Why does it not work?

#include <iostream> #include <string> using namespace std; int main(){ string a; cin >> a; size_t pos = a.find("3"); a.replace(pos, 1, "three"); cout << a; return 0; }

25th Jan 2021, 12:27 PM
Labib Wadi
Labib Wadi - avatar
6 ответов
+ 2
Because SoloLearn separates inputs by (any amount of) spaces and/or newlines for C and C++ (maybe, some more?). [edit] I just discovered that all (at least major) C++ compilers read upto space or newline when it is used thus. Try to use this line instead of "cin >> a;": cin.getline(a, 101); (you can replace 101 with any value, but 101 is the best for SoloLearn Playground) [Source and more information: https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces]
25th Jan 2021, 12:29 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 1
get Found a fix apparently getline(cin,a) works for strings cin.getline mostly works for arrays sorry for taking your time and thank you for your help.
25th Jan 2021, 1:06 PM
Labib Wadi
Labib Wadi - avatar
0
Sorry. I asked the question incorrectly it works if I do it normally but does not work with cin.Ex. If I say string a = "hello 3" it works but when I do it as input it does not.
25th Jan 2021, 12:32 PM
Labib Wadi
Labib Wadi - avatar
0
Labib Wadi, this is exactly what I said. SoloLearn and most of major C++ compilers read <string> or <char []> input until reaches newline *or space*. Use "cin.getline(string_to_store, max_length);" instead of "cin >> string_to_store;" for your program to accept input with spaces. It finishes reading until newline or when input exceeds (max_length - 1) characters. To be honest, I stuck with this problem, too. This was not small project where I was constantly adding new features, and thus I was adding some features without ability to test them until I got it by myself (now I plan to return to it). Hope it helped and you understood.
25th Jan 2021, 12:44 PM
#0009e7 [get]
#0009e7 [get] - avatar
0
get Still doesn't work. Returns an error,sorry.
25th Jan 2021, 12:55 PM
Labib Wadi
Labib Wadi - avatar