In C++, I created a new string (string class) by copying characters index wise from another string (string class) which was already initialized.
But I am unable to print this new string to the screen using cout
. Using c_str()
I am able to print it using cout
. But isn't c_str()
needed only when using printf()
because it needs a c type string?
#include <cstring>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int i;
string a,b;
cin>>a;
for(i=0;a[i]!='\0';i++){
b[i]=a[i];
}
cout<<b;
return 0;
}
EDIT: Thanks for the help! But I might not have been quite clear in my question, so these are the main problems I have. PLease read the following and if you could help me further, that would be great! (Also, I understand b=a;
is the easiest way to assign but I am trying to understand strings and hence the question.)
a) I dont know when a cpp string is null terminated and when it is not but in this case the a string after initialisation was null terminated because the loop ended and it ended after the last character of the string a because on coming out of the loop and doing cout<<a[i];
the last chararcter of a is printed.
b) Within the loop, after the assignment when I include cout<<b[i];
it does print out the value that we expect was just assigned to b[i]. So b[i] does exist for some odd reason.
c) Outside the for loop, at the end of the program, when I cout<<b[2];
it does print the third char of the string. And if I do cout<<b.c_str();
it prints out the entire string. Its only if I do cout<< b;
that nothing gets printed. Why is this?