如何通过索引将值赋值给C++字符串索引 如何通过索引将值赋值给C++字符串索引。我已经尝试过这段代码,但这并没有改变字符串的值 #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" }

如何通过索引将值赋值给C++字符串索引 如何通过索引将值赋值给C++字符串索引。我已经尝试过这段代码,但这并没有改变字符串的值 #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" },c++,string,C++,String,可以这样做,但在按索引分配字符之前,必须先调整字符串大小,使这些索引有效 str.resize(2); 将STL sstream用于stringstreams可以更轻松地附加和创建动态字符串 #include <iostream> #include <string> #include <sstream> using namespace std; void change(stringstream *ss, char value) { *ss <

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

str.resize(2);
将STL sstream用于stringstreams可以更轻松地附加和创建动态字符串

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

首先,这段代码甚至不编译。 错误:

不是标准标题。使用正义。 使用名称空间std;或前缀cout和endlwith std::。 main必须返回int,而不是void。 然后字符串的大小仍然为零,因此更改str[0]和str[1]是一种未定义的行为

要修复它,请使用std::string::resize size\u t设置其尺寸:


如何通过索引轻松将值赋值给C++字符串索引:STR〔0〕=“1”;str[1]=“2”;但是,您必须确保str[1]在此之前存在。您得到的是什么而不是预期的12?另外,请记住,字符串不仅应该知道每个元素的内容,还应该知道大小。我怀疑您打印的是空字符串,因为尽管[0]th和[1]st元素被分配,但它的大小仍然是0。您应该包含而不是iostream.h,并且该代码无法编译,因为您没有在字符串、cout和endl前面加上std:。main也应该返回int,而不是void,即使其他头文件定义了std::string。一些实现(如MSVC)没有在其他头文件(如ostream重载)中定义std::string的所有内容,因此最好包含它,以使其独立于平台/编译器。谢谢,顺便说一句,它在windows编译器c-free上编译。因此没有注意到语法错误。追加与在某个索引处更改值不同
str.resize (2);