asdjkag
asdjkag

Reputation: 448

C++ copy char to string

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?

Upvotes: 0

Views: 120

Answers (2)

Henrique Bucher
Henrique Bucher

Reputation: 4474

A few issues with your code:

  1. (not a bug) Try not to use using namespace std;

  2. 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.

  3. 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().

  4. 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

Upvotes: 4

jasraj bedi
jasraj bedi

Reputation: 161

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];
}

Upvotes: 3

Related Questions