string s = "hello" vs string s[5] = {"hello"} - c++

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
reverse(begin(s), end(s));
cout << s << endl;
return 0;
}
prints olleh
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s[5] = {"hello"};
reverse(begin(s), end(s));
cout << *s << endl;
return 0;
}
prints hello
Please help me understand why is such difference. I am newbie in c++, I am using c++ 11.
Ok, I corrected to s[5]={"hello"} from s[5]="hello" .

The first is a single string. The second is an array of five strings, and initializes all five string to the same value. However, allowing the syntax in the question is a bug (see the link in the comment by T.C.) and should normally give an error. The correct syntax would have the string inside braces, e.g. { "hello" }.
In the second program you are only printing one string of the five anyway, the first one. When you dereference an array, it decays to a pointer and gives you the value that pointer points to, which is the first element in the array. *s and s[0] are equivalent.

I think that what you are looking for is this:
int main() {
char s[] = "hello";
reverse(s, s + (sizeof(s) - 1));
cout << string(s) << endl;
return 0;
}
With char[6] you have an C-style string. Remember that theses strings must be terminated with '\0'. Therefore there is a 6th element.

Related

Managing Strings In C++

So I make an array of string pointers and put a string in at position 0 of the array. If I don't know the length of the string in word[0] how do I find it? How do I then manage that string, because I want to remove the "_." and "." part of the string so I will be left with "apple Tree".How do I resize that string? (functions like strcpy,strlen, or string.end() didn't work, I get errors like "can't convert string to char*" etc)
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int counter=0;
string* word = new string[0];
word[0] = "apple_.Tree.";
return 0;
}
Edit:what i want to do is make a dynamic array of strings(not using vector) and then edit the strings inside
string is a class, so you can use its member functions to manage it. See the documentation.
To remove characters, use std::erase (see this answer).
#include <iostream>
#include <string>
#include <algorithm>
int main() {
// Create array of 10 strings
std::string array[10];
array[0] = "apple_.Tree.";
std::cout << array[0].size() << "\n";
array[0].erase(std::remove(array[0].begin(), array[0].end(), '.'), array[0].end());
array[0].erase(std::remove(array[0].begin(), array[0].end(), '_'), array[0].end());
std::cout << array[0];
return 0;
}

I am a beginner getting an error trying to build functions

#include <iostream>
using namespace std;
int main(){
int a=4,b=8;
float r=5.55;
char c='comica';
cout<<"this is a test and value of surtd is"<<a<<".\n and value of sturd is"<<b;
cout<<"value of me is"<<'c';
return 0;
}
I did all things as shown in a lecture, but it is showing an error in the compiler.
Use the correct return 0 not return=0 and also char should hold one char not string
Code should be
#include <iostream>
using namespace std;
int main(){
int a=4,b=8;
float r=5.55;
char c='c';
cout<<"this is a test and value of surtd is"<<a<<".\n and value of sturd is"<<b;
cout<<"value of me is"<<c;
return 0;
}
char is used for storing single charecter. for storing a sequence of characters use std::string class.
string c = "comica";
//Note: Use double quotes for strings. single quotes are for charecter
Remove the quotes around variable c, Otherwise it'll print charecter c and not the value of string object c.
cout<<"value of me is"<<c;
as said in comments use return 0. return=0 is invalid.
There are multiple mistakes in your code:
Using a char variable initialized with a multi-byte character literal.
Initializing a float variable with a double literal (and then not even using the variable afterwards).
Passing a 'c' character literal to operator<< instead of your c variable.
Using a misplaced - in the return statement.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main(){
int a = 4, b = 8;
//float r = 5.55f;
string s = "comica";
cout << "this is a test and value of surtd is " << a << ".\n and value of sturd is " << b;
cout << ".\n and value of me is " << s;
return 0;
}

Splitting a string into an array of characters using a variable for the string

I'm trying to split a string into an array of individual characters. However, I would like the string to be input by the user, for which I need to define the string using a variable.
My question is, why does this work:
#include <iostream>
using namespace std;
int main() {
char arr [] = {"Giraffe"};
cout << arr[0];
return 0;
}
But this doesn't?
#include <iostream>
using namespace std;
int main() {
string word;
word = "Giraffe";
char arr [] = {word};
cout << arr[0];
return 0;
}
Thanks
Your example doesn't work because you're trying to put a std::string into an array of char. The compiler will complain here because std::string has no type conversion to char.
Since you're just trying to print the first character of the string, just use the array accessor overload of std::string, std::string::operator[] instead:
std::string word;
word = "Giraffe";
std::cout << word[0] << std::endl;
In your second example, the type of word is a std::string and there are no default type conversions from std::string to the type char.
On the other hand, the first example works because it can be interpreted as an array of char (but actually its just c-style const char *).
If, for some reason, you would want to convert std::string into the c-style char array, you might want to try something like this...
#include <iostream>
#include <string>
#include <cstring>
int main(void)
{
std::string word;
word = "Giraffe";
char* arr = new char[word.length() + 1]; // accounting for the null-terminating character
strcpy(arr, word.data());
std::cout << arr[0] << std::endl;
delete[] arr; // deallocating our heap memory
return 0;
}

String erase-append

So generally I am supposed to take a few first characters of a string and put them on the end of this string. To make it simple, let's say - first two characters. I tried something like this:
char a = mystring.at(0);
char b = mystring.at(1);
mystring.erase(0,1);
mystring.append(a);
mystring.append(b);
This of course gives an error converting from char to string. However, I have no idea how to do it, what other functions to use. Any ideas?
You can achieve this with the algorithm std::rotate:
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string s = "ABCDEFGHIJ";
std::rotate(s.begin(), s.begin() + 2, s.end());
std::cout << s << std::endl;
}
Output:
CDEFGHIJAB

Random ascii char's appearing

I was trying to write a program that stores the message in a string backwards into a character array, and whenever I run it sometimes it successfully writes it backwards but other times it will add random characters to the end like this:
input: write this backwards
sdrawkcab siht etirwˇ
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
char reverse[howLong];
for(int spot = 0; howLong >= 0; howLong--)
{
reverse[spot] = message.at(howLong);
spot++;
}
cout << reverse;
return 0;
}
The buffer reverse needs to be message.length() + 1 in length so that it can store a null termination byte. (And the null termination byte needs to be placed in the last position in that buffer.)
Since you can't declare an array with a length that is only known at runtime, you have to use a container instead.
std::vector<char> reverse(message.length());
Or better, use std::string. The STL also offers some nice functions to you, for example building the reversed string in the constructor call:
std::string reverse(message.rbegin(), message.rend();
Instead of reversing into a character buffer, you should build a new string. It's easier and less prone to bugs.
string reverse;
for(howlong; howLong >= 0; howLong--)
{
reverse.push_back(message.at(howLong));
}
Use a proper C++ solution.
Inline reverse the message:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message;
getline(cin, message);
//inline reverse the message
reverse(message.begin(),message.end());
//print the reversed message:
cout << message << endl;
return 0;
}
Reverse a copy of the message string:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message, reversed_message;
getline(cin, message);
//reverse message
reversed_message = message;
reverse(reversed_message.begin(), reversed_message.end());
//print the reversed message:
cout << reversed_message << endl;
return 0;
}
If you really need to save the reversed string in a C string, you can do it:
char *msg = (char *)message.c_str();
but, as a rule of thumb use C++ STL strings if you can.