简体   繁体   中英

How to assign value to a c++ string index by index

How to assign value to a c++ string index by index. I have tried this code but this is not changing the value of the string.

#include <iostream.h>
#include <string>

void change(string & str)
{
    str[0] = '1';
    str[1] = '2';
    // str = "12" ; // it works but i want to assign value to each index separately. 
}
void main()
{
    string str;
    change(str);
    cout << str << endl; // expected "12"
}

您可以这样做,但是在您可以按索引分配字符之前,必须首先调整字符串的大小,以使这些索引有效。

str.resize(2);

First of all, this code does not even compile. Errors:

  1. <iostream.h> is not a standard header. Use just <header> .
  2. Use using namespace std; or prefix cout and endl with std:: .
  3. main must return int , not void .

Then the size of the string is still zero, so it's an undefined behaviour to change str[0] and str[1] .

To fix it, set its dimension using std::string::resize (size_t) :

str.resize (2);

Using the STL sstream for stringstreams makes it much easier for appending and creating dynamic strings.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

void change(stringstream *ss, char value) {
    *ss << value;
}

int main() {
    stringstream stream;
    stream << "test";

    change(&stream, 't');

    cout << stream.str() << endl; //Outputs 'testt'
    return 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