简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM