When i try to add text to string i get random values.
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "333" + 4;
}
I get some random text like:↑←#
"333" is a const char [4] not std::string as you might expect(which by the way still doesn't have operator+ for int). Adding 4, you're converting it to const char * and then moving the pointer by 4 * sizeof(char) bytes, making it point to memory with garbage in it.
It happens because those are two different types and the adding operator does not work as you may expect.
If you intend to concatenate the string literals "333" with the int value of 4 than you should simply use count like:
cout << "333" << 4; // outputs: 3334
If you want to display the sum, than use string to int conversion with the stoi() function.
cout << stoi("333") + 4; // outputs: 337
Note: When using stoi(): If the string also contains literals, than the conversion will take the integer value from the beginning of the string or will raise an error in case the string begins with literals:
cout << stoi("333ab3") + 4; // same as 333 + 4, ignoring the rest, starting a
cout << stoi("aa333aa3") + 4; // raise error as "aa" can't be casted to int
As you want to add text to text, solution would be to use proper types:
cout << std::string( "333" ) + "4";
or for c++14 or later:
using namespace std::string_literals;
cout << "333"s + "4"s;
I honestly do not know what you are trying to achieve by adding int to string. In case you want to add 333+4, you need to Parse string in to int like this :
edit:Typo
#include
using namespace std;
int main()
{
cout << std::stoi("333") + 4;
}
Related
#include <iostream>
#include <string.h>
using namespace std;
void crypt(char* sMsg)
{
cout << "Original Message: '" << sMsg << "'" << endl;
int length = strlen(sMsg);
char sMsg_Crypt[3][length];
/* sMsg_Cryp[3]
[0] CRYPT LETTERS, ASCII + 3
[1] INVERT CHAR
[2] HALF+ OF SENTENCE, ASCII - 1
*/
for (int i=0; i<length; i++)
{
if (isalpha((int)sMsg[i]))
sMsg_Crypt[0][i] = sMsg[i] + 3; // DO ASCII + 3
else
sMsg_Crypt[0][i] = sMsg[i];
}
cout << "Crypt[0]: '" << sMsg_Crypt[0] << "'" << endl;
}
int main()
{
char sMsg[256];
cin.getline(sMsg,256);
crypt(sMsg);
return 0;
}
Input:
Hello World! Testing the Cryptography...
Output:
Original Message: 'Hello World! Testing the Cryptography...'
Crypt[0]: 'Khoor Zruog! Whvwlqj wkh Fu|swrjudsk|...Çio'
Why this Çio is comming out??
For starters variable length arrays like this
int length = strlen(sMsg);
char sMsg_Crypt[3][length];
is not a standard C++ feature.
You could use at least an array of objects of the type std::string like for example
std::string sMsg_Crypt[3];
Nevertheless the problem is that the array sMsg_Crypt[0] dies not contain a string. That is you forgot to append inserted characters in the array with the terminating zero character '\0'.
You could write after the for loop
sMsg_Crypt[0][length] = '\0';
provided that the array (if the compiler supports VLA) is declared like
char sMsg_Crypt[3][length+1];
Firstly, you can't define a static char array like this: char sMsg_Crypt[3][length];. That is because the length is not a const type, meaning the size of the array will be sMsg_Crypt[3][0] (this is because the size is not known at compile time). In MSVC, it'll flag an error (by IntelliSense). Since you know the size beforehand (256), you can replace the length with 256.
The second fact is that you're using C++ and you have access to std::string. So without using a char buffer, use std::string instead. It would look something like this: std::string sMsg_Crypt[3];
The last fact is that, for a string to be read correctly, it needs to be null-terminated ('\0' at the end). This means that the ending character must be '\0'. In the case of std::string, it does it for you.
I tried making a small program using the libraries "iostream" and "String" to display a given string backwardly as the output on the command prompt. I used a recursive returning-value (string) function to perform the whole process of getting the given string in backward and returning it to the main function to be displayed on screen, as you can see below:
#include <iostream>
#include <string>
using namespace std;
string rev(string, int);
int main() {
string let;
cout << "Enter your string: ";
cin >> let;
cout << "The string in reverse is: " << rev(let, let.length());
cout << endl;
return 0;
}
string rev(string x, int y) {
if (y != 0 )
return x[y - 1] + rev(x, y - 1);
else
return "\0";
}
What I don't get about the process, is that while the concatenation performed on the rev function, recursively, and with the char variables works correctly and returns the string in backward to the main function, trying to concatenate the char variables normally like this gives rubbish as the output:
#include <iostream>
#include <string>
using namespace std;
int main() {
string hd;
string ah = "foo";
hd = ah[2] + ah[1] + ah[0];
cout << hd << endl;
return 0;
}
And even if I add to the "hd" chain "\0", it still gives rubbish.
Your first example implicitly converts characters to strings and uses appropriate operator +
While your second example is adding up characters
https://en.cppreference.com/w/cpp/string/basic_string/operator_at
returns reference to character at position
Writing instead
hd = ""s + ah[2] + ah[1] + ah[0];
will, informally speaking, put + into a "concatenation mode", achieving what you want. ""s is a C++14 user-defined literal of type std::string, and that tells the compiler to use the overloaded + operator on the std::string class on subsequent terms in the expression. (An overloaded + operator is also called in the first example you present.)
Otherwise, ah[2] + ah[1] + ah[0] is an arithmetic sum over char values (each one converted to an int due to implicit conversion rules), with the potential hazard of signed overflow on assignment to hd.
How about making use of everything that's already available?
string rev(const string &x) { return string{x.rbegin(), x.rend()}; }
Reverse iterators allow you to reverse the string, and the constructor of string with 2 iterators, constructs an element by iterati from begin to end.
The string str_hex contains the hex-values for the letters A-J, which corresponds to the decimal values 65-74. I'm trying to cast each hex-value to its decimal value following this example. It works nice for the std::cout case inside the for-loop, but the output-std::string still has the ascii-values. Why does this not work or is there a nicer/more proper way to build my output string?
#include <string>
#include <iostream>
#include <stdint.h>
int main()
{
std::string str_hex("\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b", 10);
std::string str_output = "";
for (int i = 0; i < 10; ++i)
{
uint8_t tmp = str_hex[i];
str_output.append(1, (unsigned)tmp);
std::cout << "cout+for: " << (unsigned)tmp << std::endl;
if(i<9)
str_output.append(1, '-');
}
std::cout << std::endl << "cout+str_append: " << str_output << std::endl;
return 0;
}
Compiling and running the program gives the following output:
cout+for: 65
cout+for: 66
cout+for: 67
...
cout+str_append: A-B-C-D-E-F-G-H-I-J
The desired output is:
cout+str_append: 65-66-67-68-...
The method string::append accepts, among the various overload, a size_t and a char, see reference.
string& append (size_t n, char c);
Therefore, in your code line
str_output.append(1, (unsigned)tmp);
you are implicitly converting the unsigned tmp to a char, i.e., to a single letter. To obtain the output you want, you have to convert tmp to a string containing the number, and then append it to str_output. You can do that by using
str_output+=std::to_string(tmp);
instead of str_output.append(1, (unsigned)tmp);.
You have to change your string append to for the change from a number to its "string":
str_output.append(std::to_string(tmp));
It's not one character that you want to add, but a string representing the number.
I'm working on this code that takes a numeric string and fills an array with each "digit" of the string. The issue I'm having is trying to convert an integer to a string. I tried using to_string to no avail.
Here is the code (note this is pulled from a larger program with other functions):
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <typeinfo>
int fillarr(int &length) {
int arr[length];
string test = "10010"; //test is an example of a numeric string
int x = 25 + ( std::rand() % ( 10000 - 100 + 1 ) );
std::string xstr = std::to_string(x); //unable to resolve identifier to_string
cout << xstr << endl;
cout << typeid (xstr).name() << endl; //just used to verify type change
length = test.length(); //using var test to play with the function
int size = (int) length;
for (unsigned int i = 0; i < test.size(); i++) {
char c = test[i];
cout << c << endl;
arr[int(i)] = atoi(&c);
}
return *arr;
}
How can I convert int x to a string? I have this error: unable to resolve identifier to_string.
As mentioned by user 4581301, you need an #include <string> to use string functions.
The following, though is wrong:
arr[int(i)] = atoi(&c);
The atoi() will possibly crash because c by itself is not a string and that mean there will be no null terminator.
You would have to use a buffer of 2 characters and make sure the second one is '\0'. Something like that:
char buf[2];
buf[1] = '\0';
for(...)
{
buf[0] = test[i];
...
}
That being said, if your string is decimal (which is what std::to_string() generates) then you do not need atoi(). Instead you can calculate the digit value using a subtraction (much faster):
arr[int(i)] = c - '0';
Okay I modified my code a bit per suggestion from everyone and ended up handling the conversion like this:
string String = static_cast<ostringstream*>( &(ostringstream() << x) )->str();
cout << String << endl;
When i try to add text to string i get random values.
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "333" + 4;
}
I get some random text like:↑←#
"333" is a const char [4] not std::string as you might expect(which by the way still doesn't have operator+ for int). Adding 4, you're converting it to const char * and then moving the pointer by 4 * sizeof(char) bytes, making it point to memory with garbage in it.
It happens because those are two different types and the adding operator does not work as you may expect.
If you intend to concatenate the string literals "333" with the int value of 4 than you should simply use count like:
cout << "333" << 4; // outputs: 3334
If you want to display the sum, than use string to int conversion with the stoi() function.
cout << stoi("333") + 4; // outputs: 337
Note: When using stoi(): If the string also contains literals, than the conversion will take the integer value from the beginning of the string or will raise an error in case the string begins with literals:
cout << stoi("333ab3") + 4; // same as 333 + 4, ignoring the rest, starting a
cout << stoi("aa333aa3") + 4; // raise error as "aa" can't be casted to int
As you want to add text to text, solution would be to use proper types:
cout << std::string( "333" ) + "4";
or for c++14 or later:
using namespace std::string_literals;
cout << "333"s + "4"s;
I honestly do not know what you are trying to achieve by adding int to string. In case you want to add 333+4, you need to Parse string in to int like this :
edit:Typo
#include
using namespace std;
int main()
{
cout << std::stoi("333") + 4;
}