I am trying to replace the W with the number 5 (in this example). However, when I try, I only get the the ascii value of 5 to replace the W, instead of the number 5 itself. How would I fix this?
NOTE: I this is a shortened example from a longer project. I need to access the number in nums[1].
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[3] {4,5,6};
string str = "HELLO WORLD";
cout << str << endl;
str[6] = nums[1];
cout << str << endl;
return 0;
}
Output:
HELLO WORLD
HELLO ♣ORLD
CodePudding user response:
You are trying to store an int
where a char
is expected. Integer 5
(interpreted as character '♣'
in your console's charset) and character '5'
(integer 53
in ASCII) are not the same value.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch0 = '5';
string str = "HELLO WORLD";
cout << str << endl;
str[6] = ch0;
cout << str << endl;
return 0;
}
CodePudding user response:
You can convert a digit to an ASCII character: char c = '0' 5
(gives you '5'
).
This is your code fixed:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[3] {4,5,6};
string str = "HELLO WORLD";
cout << str << endl;
str[6] = '0' nums[1];
cout << str << endl;
return 0;
}
However, if you intend to insert an integer as you title says, you have to do this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[3] {4,15,6};
string str = "HELLO WORLD";
cout << str << endl;
str = str.substr(0, 6) std::to_string(nums[1]) str.substr(7);
cout << str << endl;
return 0;
}
Here is a more sophisticated version which tries to use existing capacity:
#include <iostream>
#include <string>
#include <algorithm>
// don't ever do it with std
// using namespace std;
size_t count_digits(int num)
{
int digits = 0;
do {
num /= 10;
digits ;
} while (num);
return digits;
}
void insert_number(std::string& str, size_t indx, int num)
{
const size_t digits = count_digits(num),
oldSize = str.size();
// insert will reallocate only if capacity is not enough
str.insert(str.size(), digits - 1, '0');
// move the end of string right by rotating (rewriting characters)
auto iterBegin = std::next(str.begin(), indx),
iterNext = std::next(str.begin(), oldSize);
std::rotate(iterBegin, iterNext, str.end());
// write our string from integer to the designated space
const auto &strInteger = std::to_string(num);
for (size_t iStr = indx, iInt = 0; iInt != strInteger.size(); iInt, iStr)
str[iStr] = strInteger[iInt];
}
int main()
{
int nums[3] {4, 48152342, 6};
std::string str = "HELLO WORLD LOOOOONG STRIIING";
str.reserve(str.capacity() 20); // strings don't preallocate more space after construction
std::cout << str << std::endl;
std::cout << "capacity before: " << str.capacity() << std::endl;
insert_number(str, 6, nums[1]);
std::cout << str << std::endl;
std::cout << "capacity after: " << str.capacity() << std::endl;
return 0;
}