I want to get string by cin>>
and then I'd like to print it by printf
. But printf
is giving some unexpected result. How can I fix it?
string *planet;
planet = new string;
cout << "Enter planet name:"<<endl;
cin >> *planet; //Saturn
cout<< *planet<<endl; //Saturn
printf("Your planet is %s",planet); //Your planet is аk
I now, there is no strings in C there, instead it realized by char[]
. printf
accepts name of array, which is an address of a first element of it, thus I'm giving a pointer to string to it, which is an array of char and its name is the address of a first element too. So it must be the same.
In connection with it, secondary question has appeared: why can't I get certain element of string as it is an array?
string *planet;
planet = new string;
cout << "Enter planet name:"<<endl;
cin >> *planet;
cout<< *planet<<endl; //Helion
string str = {"Helion"};
cout<< str[2]<<endl; //l
cout<< planet[2]<<endl; //error Process returned -1073741819 (0xC0000005)
string
is not an array, it is a class. Do not use it like a pointer. To get a C-style string, use c_str()
:
string planet;
cin >> planet;
printf("Your planet is %s",planet.c_str());
cout<< planet[2]<<endl;
User contributions licensed under CC BY-SA 3.0