I wrote a string assignment in c++, but I don't know why it output s[0], while output none of s?
The code is following, and the output is: h**hello*
#include <iostream>
#include <string>
using namespace std;
int main(){
string s;
s[0] = 'h';
s[1] = 'i';
string s2;
s2="hello";
cout <<s[0]<<"*"<< s << "*" << s2<<"*";
return 0;
}
For std::string, operator[] is only valid to index into existing data of the string. It does not cause the string to grow, it simply goes out of bounds if the string isn't already that size. To append to a string, you have several options, but to append single chars like you're doing, you'd do this:
int main(){
std::string s;
s += 'h';
s += 'i';
...
Each application of operator += causes the size of the string to grow.
Related
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;
}
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.
Here is my code
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
string s,s1;
cin>>s;
s1[0]=s[1];
s1[1]=s[2];
s1[2]=s[3];
s1[3]='\0';
cout<<s1<<endl;
return 0;
}
s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?
Probably, the easiest way to accomplish OP's task is to use a library function like substr() which takes care of all the details the posted code is missing (and already pointed out):
memory management. The second string s1 is empty, so trying to write its first four (unallocated) elements is undefined behavior. In general, s1 should be resized to the needed length.
null terminator. A std::string can manage it's internal representation and always returns a null-terminated string via its member functions c_str and data (since C++11).
That's how it could be done:
#include <iostream>
#include <string>
int main()
{
std::string s;
std::cin >> s;
std::string s1;
std::string::size_type start_pos = 1,
count = 3;
if ( s.size() > start_pos )
s1 = s.substr(start_pos, count);
std::cout << s1 << '\n';
}
s1 doesn't have any characters. You're trying to change the value of characters that do not exist.
Your program has undefined behaviour, and might just as easily open a llama zoo, reverse the polarity of the Earth's magnetic field, or solve cold fusion in the bath.
Make s1 the correct size before writing things to it;
Don't write a '\0' to the end; this is not a C string; that is unnecessary. C++ strings look after themselves.
Here's an example:
#include <iostream>
#include <cassert>
int main()
{
std::string s, s1;
std::cin >> s;
assert(s.size() >= 4);
s1.resize(3);
s1[0] = s[1];
s1[1] = s[2];
s1[2] = s[3];
std::cout << s1 << std::endl;
}
live demo
You can not assign as s1[0] = s[1]
Correct way is using assign function as:
string s,s1;
cin>>s;
s1.assign(s.begin()+1,s.begin()+4);
cout<<s1<<endl;
String assignment cannot be done by assigning indexes without fixing or defining the size of the string. It may cause a string subscript error. If you want to do this, I think string concatenation is the best method; that is, by adding substrings or string indexes into string. I've given some code below that uses the string concatenation method.
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main()
{
string s,s1="";
cin>>s;
s1= s1 + s[1];
s1= s1 + s[2];
s1= s1 + s[3];
cout<<s1<<endl;
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string output;
string words;
int i;
int main()
{
cin >> words; // gets words from user
output = ""; // readys the output string
i = 0; // warms up the calculator
int size = words.size(); // size matters
while (i <= size) { // loops through each character in "words" (can't increment in the function?)
output += ":regional_indicator_" + words[i] +':'; // appends output with each letter from words plus a suffix and prefix
++i;
}
cout << output << endl; // prints the output
return 0;
}
My intentions with this code is decently clear I'd like to think. Simply take a sentence, replace all characters with that character + a suffix and prefix.
My problem is that, when ran in the debugger, I'll input "hello world" and the program will output "osss".
I have absolutely no education in C++ and am at a total loss here. Is it my ++i?
This line:
output += ":regional_indicator_" + words[i] +':'; // appends output with each letter from words plus a suffix and prefix
doesn't work. The overloading of the + operator for string concatenation only works if one of the arguments is a std::string. But you're trying to use it with a C-string literal and a char. Change that to:
output += "regional_indicator_";
output += words[i];
output += ':';
This uses the += overloading of std::string for each part, and does what you want.
Also, if you want to read a whole line, not just a single word, use:
getline(cin, words);
#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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ String Length?
I really need a help now. How to accept string as input and find the length of the string? I just want a simple code just to know how it works. Thanks.
Hint:
std::string str;
std::cin >> str;
std::cout << str.length();
in c++:
#include <iostream>
#include <string>
std::string s;
std::cin >> s;
int len = s.length();
You can use strlen(mystring) from <string.h>. It returns the length of a string.
Remember: A string in C is an array of chars which ends in character '\0'. Providing enough memory is reserved (the whole string + 1 byte fits on the array), the length of the string will be the number of bytes from the pointer (mystring[0]) to the character before '\0'
#include <string.h> //for strlen(mystring)
#include <stdio.h> //for gets(mystring)
char mystring[6];
mystring[0] = 'h';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';
strlen(mystring); //returns 5, current string pointed by mystring: "hello"
mystring[2] = '\0';
strlen(mystring); //returns 2, current string pointed by mystring: "he"
gets(mystring); //gets string from stdin: http://www.cplusplus.com/reference/clibrary/cstdio/gets/
http://www.cplusplus.com/reference/clibrary/cstring/strlen/
EDIT: As noted in the comments, in C++ it's preferable to refer to string.h as cstring, therefore coding #include <cstring> instead of #include <string.h>.
On the other hand, in C++ you can also use C++ specific string library which provides a string class which allows you to work with strings as objects:
http://www.cplusplus.com/reference/string/string/
You have a pretty good example of string input here: http://www.cplusplus.com/reference/string/operator%3E%3E/
In this case you can declare a string and get its length the following way:
#include <iostream>
#include <string>
string mystring ("hello"); //declares a string object, passing its initial value "hello" to its constructor
cout << mystring.length(); //outputs 5, the length of the string mystring
cin >> mystring; //reads a string from standard input. See http://www.cplusplus.com/reference/string/operator%3E%3E/
cout << mystring.length(); //outputs the new length of the string