This question already has answers here:
String plus Char - what is happening?
(5 answers)
Closed 8 months ago.
#include <iostream>
#include <conio.h>
#include <stack>
#include <string>
using namespace std;
int main{
string h = "";
h = ("" + 'a');
cout << h;
return 0;
}
Output: "nity\VC\Tools\MSVC\14.29.30133\include\xstring"
I am honestly clueless as to what to do. I've never had this happen before.
Note: I've found a way to avoid this by appending the char like this:
string g="";
g+='a';
Regardless, why is this?
"" is a literal of type const char[1], which is the identical as const char* in most regards. 'a' is a literal of type char, which is really just an integer type. So if you do "" + 'a', you will get a pointer to 'a' (=97 in ASCII) characters after wherever the compiler decides to put the "". Which is then converted to an std::string.
In the working example, you convert the "" literal to std::string first, then add a char to it. std::string overloads the + and += operators, so it will produce a reasonable result.
Related
I'm trying to put a character on the stack, but it is putting the ASCII integer value of the character. What is causing this and how can I get an actual character onto the stack?
Here is some simple code to show what I mean:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> v;
std::string s = "ABCDEF";
char c = s[0];
v.push_back(std::to_string(c));
std::cout << v[0] << std::endl;
}
std::to_string doesn't have a conversion from char, but it does have a conversion from int. So c will implicitly be converted to an int with the corresponding ASCII value, and this is converted to a std::string.
If you want to push_back the character c as a std::string, you can do:
v.push_back({c});
Here's a demo.
This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 2 years ago.
I have written a simple C++ code, and its working fine. But I don't know how it is working. I am just replacing "l" with "r" using myfun().
The return type of myfun() is char*. If I am returning &(str[0]), that is, only the address of the first element of the array, then why is it printing the complete string "herloworld"? Please explain what return &(str[0]); is doing.
#include <iostream>
using namespace std;
char* myfun(char str[])
{
str[2] = 'r';
return &(str[0]);
}
int main()
{
char str[] = "helloworld";
char* word;
word = myfun(str);
cout << word;
}
The operator << is overloaded for the type char * such a way that it expects that the used pointer of the type char * points to the first character of a string.
So the operator outputs all characters of the passed string until the zero character '\0' is encountered.
Also pay attention to that arrays used in expressions with rare exceptions are converted to pointers to their first elements.
So this call
word = myfun(str);
is equivalent to
word = myfun( &str[0]);
On the other hand, a function parameter having an array type is implicitly adjusted to pointer to the element type.
So this function declaration
char* myfun(char str[]);
is equivalent to the following declaration
char* myfun(char *str);
The both declarations declare the same one function.
And within the function instead of this return statement
return &(str[0]);
you could write
return str;
Correspondingly in main you could write
cout << myfun(str);
without declaring and using the intermediate pointer word.
This question already has answers here:
C++ Adding String Literal to Char Literal
(8 answers)
Closed 5 years ago.
In case 1 the output is blank when I initialize a string like this:
#include <iostream>
#include<string>
using namespace std;
//CODE 1
int main()
{
string s="hello" + 'c';
cout<<s<<endl;
return 0;
}
but when I write it this way it works fine:
#include <iostream>
#include<string>
using namespace std;
//CODE 2
int main()
{
string s="hello";
char k='c';
s+=k;
cout<<s<<endl;
return 0;
}
Now I am confused as in another question asked on stack overflow it says that there is no difference between string and std::string when namespace std is used, those answers go by saying that -> There is no functionality difference between string and std::string because they're the same type
std::string vs string in c++
whereas the answers provided for this question are pointing differences:
compiler is g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
When you have
string s="hello" + 'c';
It's equal to
string s=("hello" + 'c');
With ASCII encoding it's the same as
string s=("hello" + 99);
which is the same as
string s=(&"hello"[99]);
That is, you get a pointer to the 100:th element of the string "hello", which only have six elements (don't forget the terminator).
Going out of bounds leads to undefined behavior.
Because "string" is not a std::string but a const char*, and a pointer plus a number (a character is "just" a number) uses pointer arithmetic, so after your addition, you'll get a const char* which points possibly to garbage memory after your string literal.
The second example works because in this case, s is a std::string which has a operator += for char and does not use pointer arithmetic.
The codes are not the same. In
string s="hello" + 'c';
"hello" is not a std::string. It is a string literal and has the type of const char[N]. When you add a character to it to the array decays to a pointer and you are doing pointer arithmetic. That arithmetic is going past the end of the string literal so it is undefined behavior.
In order to get the first code to act like the second example you need to make "hello" a string. You can use a user defined literal for std::string like
string s = "hello"s + 'c';
or just use a constructor call like
string s = std::string("hello") + 'c';
The expression "hello" + 'c'; is adding a char type to a const char[6] type, with an obscure result. Formally the first argument decays to a const char* pointer, and c is added to that pointer using the normal rules of pointer arithmetic. The behaviour is probably undefined, since the numeric value of c is, in all encodings I've ever come across, a value greater than 6, so you end up attempting to index an element outside the const char array "hello".
In the second version, you are exploiting the overloaded += operator of the std::string class taking a char as an argument, and the character c is concatenated to that string.
"hello" + 'c' gives a pointer past the end of "hello" (e.g. assuming an ASCII character set, 'c' has the numeric value 99, and "hello" + 99 gives a pointer to a memory location that is 99 characters past the 'h' in "hello").
Using such a pointer to initialise an std::string gives undefined behaviour.
The "CODE 2" works std::string has an operator+=() that accepts a char, and appends it to the end of the string.
This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 9 years ago.
#include <iostream>
using namespace std;
int main() {
string a = "1234"; //How this string convert in integer number
system("pause");
return EXIT_SUCCESS;
}
string a = "1234";
How this convert in integer
You can use std::stoi() to convert a std::string to an int.
#include <iostream>
#include <string>
int main() {
std::string a = "1234"; //How this string convert in integer number
int b = std::stoi(a);
system("pause");
return EXIT_SUCCESS;
}
If you have C++11 and onwards, use
int n = std::stoi(a);
(Pre C++11, you could use std::strtol;)
You could use boosts lexical cast
#include <boost/lexical_cast.hpp>
std::string str_num = "12345";
int value = 0;
try
{
value = boost::lexical_cast<int>(str_num);
}
catch(boost::bad_lexical_cast &)
{
// error with conversion - calling code will deal with
}
This way you can easily modify the code to deal with float or double if your string contains those types of numeric value also
You have to use std::stoi:
#include <iostream>
#include <string>
std::string s = "123";
int number= std::stoi(s);
The C++ Standard has a special function
int stoi(const string& str, size_t *idx = 0, int base = 10);
Probably you can try this
string a = "28787" ;
int myNumber;
istringstream ( a) >> myNumber;
See or you can search for stoi function and see how it can be used. Probably It can work but never try because I dont have the compiler of c++
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Alternative to itoa() for converting integer to string C++?
How do you change an integer to a string in c++?
Standard C++ library style:
#include <sstream>
#include <string>
(...)
int number = 5;
std::stringstream ss;
ss << number;
std::string numberAsString(ss.str());
Or if you're lucky enough to be using C++11:
#include <string>
(...)
int number = 5;
std::string numberAsString = std::to_string(number);
You could use snprintf(char *str, size_t size, const char *format, ...) to get a char[], then use string(char*) get string.
Of courseļ¼there're other ways.