I am trying to assign the value to string and then access it, but for the 1st case i didnt get output as wanted....
#include <iostream>
#include <string>
using namespace std;
int main(){
string abc;
abc[0] = 'm';
cout << "str1 : " << abc << endl;
cout << "str1 : " << abc[0] << endl;
//-----------------------------------
string xyz;
xyz = "village";
cout << "str2 : " << xyz << endl;
cout << "str2 : " << xyz[0] << endl;
return 0;
}
Output Should Be :
str1 : m
str1 : m
str2 : village
str2 : v
But Actually It Is :
str1 :
str1 : m
str2 : village
str2 : v
CodePudding user response:
In the first case you are replacing the null
-terminator (which each string has at end, to mark end), with m
, and probably causing a lot of random output, if not SIGSEG
crash and/or undefined behavior.
Solutions
Array style
std::string myVariable;
// ...
myVariable.resize(3, '\x0');
myVariable[0] = 'm';
myVariable[1] = 'a';
myVariable[2] = 'x';
// And index 3 is already null-terminator (no need to set manually to zero).
What you should do instead
If speed is not a concern, and you just want stability and ease of use, try something like:
abc = 'm';
OR
abc.append(1, 'm');
CodePudding user response:
There is a mistake in your program as described below.
Mistake
string abc; //this creates a **0 sized** default constructed string object
abc[0] = 'm';// incorrect because you're trying to assign to the 0th index of the string object abc but note that there is no 0th index because the string has 0 size.
Note that the statement
abc[0] = 'm';
is incorrect because at the moment the string object abc
has 0 size and you're trying to access the 1st element(which have 0th index). But wait, how can you access the 1st element(or 0th index) of a string that doesn't have any element because it is of size 0.
Solution 1
Instead of assigning to the 0th index you can append to the string abc
using
abc = 'm';
Solution 2
You can also create a std::string
with a particular size(length) and element as follows:
std::string abc(1, 'm'); //now abc has size(length) of 1 and has the element(0th element) as "m".
with this you don't need to use the assignment you're doing. That is now you don't need abc[0] = 'm';
CodePudding user response:
Your code has undefined behavior. After string abc;
abc
is empty and contains no elements. abc[0] = 'm';
is trying to perform assignment on abc'
s 1st element which doesn't exist.
You might want
abc = 'm'; // append 'm' to abc
or
abc.append(1, 'm'); // append 'm' to abc