The real problem here is not that you can't read or can't print the string, is that you are writing to unallocated memory. operator[]
, which is what you are using when you do something like a[i]=ch
, does not do any kind of boundary checking and thus you are causing undefined behavior. In my machine, nothing is printed, for instance.
In short, you need to make sure that you have space to write your characters. If you are certain that you are going to read 5 characters (and adding a \0 at the end, making it 6 in length), you could do something like this:
std::string a(6, '\0')
If you are uncertain of how many characters you are going to read, std::string
is ready to allocate space as need, but you need to use std::push_back
to give it a chance to do so. Your loop contents would be something like:
cin >> ch;
a.push_back(ch);
If you are uncertain where the std::string
object is coming from (as in, this is library code that accepts a std::string
as an argument, you could use at(i)
(e.g, a.at(i) = ch
instead of a[i] = ch
), which throws an exception if it is out of range.