int main()
{
string sample = "abcdef";
string result;
result[0]='a';
cout<<result[0];
}
I am trying to copy a char into a string result; the output should be a displayed. but there is no display.and no error message.
direct copy is working // result=sample; how is this code wrong?
CodePudding user response:
A few issues with your code:
(not a bug) Try not to use
using namespace std;
result
is initially empty so assigning to a specific character position will actually be a bug. If you append to it with the=
operator then it works as expected.It should not be an issue but the std::cout buffer might not be flushed on some particular occasions. You can force to flush with
std::cout.flush()
.Always end with a newline for clarity
#include <iostream>
int main()
{
std::string sample = "abcdef";
std::string result;
result ='a';
std::cout << result << std::endl;
}
Produces:
Program returned: 0
Program stdout
a
Godbolt: https://godbolt.org/z/ocvGP6333
CodePudding user response:
This should result in run time error while accessing
result[0]
hence you should use
result ="a";
Also, you are not using sample variable in your code, if you intend to copy the first char from sample to result, you can use
int main() {
string sample = "abcdef";
string result;
result =sample[0];
cout<<result[0];
}