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;
Related
After calculating a number, I need to get several digits of this one. I cast it to string, and print a digit, but in one piece of code, it works correct (prints only one digit), but after I equate it to another variable, the program prints 2 digits.
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <ctime>
#include <sstream>
using namespace std;
int main()
{
time_t seconds;
int res = 0;
seconds = time(NULL);
double nump = seconds;
cout.precision(45);
for (int i = 1; i <= 100; i++) {
nump = nump /10;
}
std::ostringstream strs;
strs.precision(55);
strs << nump;
std::string str = strs.str();
cout << str[str.size() - 9] << endl; // here we get a gidit from the string (e.g. 5)
res = str[str.size() - 9];
cout << res << endl; // here we get a number (e.g. 49)
system("pause");
return 0;
}
I cant understand whats going on. Please help!
That's because here
res = str[str.size() - 9];
You are storing the value of a char in an int. Printing the same value as int can have different results when you send it to std::cout than when you print it as char. For integers this operator is called, while for chars this operator is called instead.
In your example, you probably have a value of '1' (which is 49 in ASCII). When you print it as a char it prints 1, and when you print it as an int, it prints 49.
One way to solve this problem is to make int res be a char instead.
I am trying to make a program that turns a string into encryption by going ten letters ahead of each letter. https://gyazo.com/86f9d708c2f02cf2d70dbc1cd9fa9a06 I am doing part 2. When I input "helloworld" something like 0x45 something comes up. Please help! This is due soon!
I am tried messing around with the for loops but it didn't help.
#include <iostream>
using namespace std;
int main()
{
//Input Message
cout << "Enter a message" << endl;
string message;
getline(cin, message);
//Convert Message to Numbers
int numMess[message.length()];
for (int i = 0; i<message.length(); i++) {
numMess[i] = (int)message[i];
}
cout << numMess << endl;
//Encrypt Number Message by adding ten to each one
int encryptNumMess[message.length()];
for (int a = 0; a < message.length(); a++){
encryptNumMess[a] = numMess[a] + 10;
if (encryptNumMess[a] > 122) {
encryptNumMess[a] = 97;
}
}
cout << encryptNumMess << endl;
//Convert Encrypted Number Message to letters
string encryption[message.length()];
for (int b = 0; b<message.length(); b++) {
encryption[b] = (char)encryptNumMess[b];
}
cout << encryption << endl;
return 0;
}
I expect when I type "helloworld" the final product will be "rovvygybvn"
If you are willing to scrap the hand-coded loops, you can use the STL algorithms such as std::transform to accomplish this:
But first, there are a few things you should do:
Don't use magic numbers such as 122, 97, etc. Instead use the actual character constants, i.e a, b, etc. However if we assume ASCII, where the alphabetic character codes are contiguous, your particular program could simply use a constant string to denote the alphabet, and then use simple indexing to pick out the character.
const char *alphabet = "abcdefghijklmnopqrstuvwxyz";
Then to get the letter a, a simple subtraction is all that's required to get the index:
char ch = 'b';
int index = ch - 'a'; // same as 'b' - 'a' == 98 - 97 == 1
std::cout << alphabet[index]; // will print 'b'
Given this, the next thing is to figure out what character is reached if you add 10 to the value, and if greater than 26, wrap around to the beginning of the alphabet. This can be done using modulus (remainder after division)
char ch = 'x';
int index = (ch - 'a' + 10) % 26; // Same as ('x' - 'a' + 10) % 26 == (120 - 97 + 10) % 26 == 33 % 26 == 7
std::cout << alphabet[index]; // will print 'h'
The next thing is to figure out the opposite, where given an encrypted character, you have to find the unencrypted character by subtracting 10. Here this wraps the opposite way, so a little more work needs to be done (not shown, but code sample reflects what is done).
Putting this all together, and using std::transform and lambdas, we get the following small program:
#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
#include <cmath>
int main()
{
//Input Message
const char *alphabet="abcdefghijklmnopqrstuvwxyz";
std::string message = "helloworld";
std::string result;
// set the encrypted string using the formula above and std::transform
std::transform(message.begin(), message.end(), std::back_inserter(result),
[&](char ch) { return alphabet[(ch - 'a' + 10) % 26]; });
std::cout << "Encrypted: " << result << '\n';
// convert back to unencrypted using the above formula and std::transform
std::string result2;
std::transform(result.begin(), result.end(), std::back_inserter(result2),
[&](char ch)
{ int index = ch - 'a' - 10; index = index < 0?26 - (abs(index) % 26):index % 26; return alphabet[index];});
std::cout << "Unencrypted: " << result2;
}
Output:
Encrypted: rovvygybvn
Unencrypted: helloworld
This code works for encrypt, if you want to decrypt you should chande newAlphabet and oldAlphabet
I comment in the code that which newAlphabet and oldAlphabet are for encrypt and which are for decrypt
#include <windows.h>
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
// For Encrypt
string newAlphabet = "abcdefghijklmnopqrstuvwxyz";
string oldAlphabet = "klmnopqrstuvwxyzabcdefghij";
// For Decrypt
//string newAlphabet = "klmnopqrstuvwxyzabcdefghij";
//string oldAlphabet = "abcdefghijklmnopqrstuvwxyz";
string input = "";
string output = "";
getline(cin, input);
int inputLen = input.size();
if (oldAlphabet.size() != newAlphabet.size())
return false;
for (int i = 0; i < inputLen; ++i)
{
int oldCharIndex = oldAlphabet.find(tolower(input[i]));
if (oldCharIndex >= 0)
output += isupper(input[i]) ? toupper(newAlphabet[oldCharIndex]) : newAlphabet[oldCharIndex];
else
output += input[i];
}
cout << output << endl;
return 0;
}
As others have already mentioned int numMess[message.length()]; is not valid c++.
If it works for you, you're using compiler extension which you really shouldn't rely on. The correct way would be:
std::vector <int> numMess(message.length());
Look up the std::vector reference for more info.
Next, int encryptNumMess[100]; creates a C array style array. encryptNumMess is the base pointer to the array. when you try std::cout << encryptNumMess it'll output the pointer value, NOT the array. You'll need a for loop for doing that, like so :
for(int i = 0; i < 100; ++i)
std::cout << encryptNumMess[i] << " ";
std::cout << endl;
The above also works when you convert this to a vector like we did with numMess whereas in that case, std::cout << encryptNumMess wouldn't even compile.
Thirdly, string encryption[100] creates an array of 100 strings! Not a string of size 100. To do that:
std::string foo(message.length(), '\0');
We have to specify what character to fill the string with. Thus us '\0'.
And now, for the string, to output it, you may use std::cout << foo.
Lastly, since arithmetic is allowed on char, the entire program may be shortened to just this
#include <iostream>
int main()
{
// Input Message
std::cout << "Enter a message" << std::endl;
std::string message, encryption;
getline(std::cin, message);
// Resize encryption string to the desired length
encryption.resize(message.length());
// Do the encryption
for(size_t i = 0; i < message.length(); ++i) {
encryption[i] = message[i] + 10;
if (encryption[i] > 122) {
encryption[i] = 97;
}
}
// Output the string
std::cout << encryption << std::endl;
return 0;
}
Of course, your encryption algorithm is still not correct as per instructions, but I'll leave that for you to figure out. I believe #PaulMcKenzie has already told you most of how to fix it, and also to not use magic numbers.
I need to write a program that prompts the user to input a string, then determine the middle of the string, and generate a new string which swaps the two halves of the string and then output the results.
So far I have
int main(void) {
char *string = NULL;
char temp[1000];
cout << "Please enter a string" << endl;
cin.getline(temp, 999);
int length = strlen(temp);
string = new char[length];
strcpy(string,temp);
length = length / 2;
return EXIT_SUCCESS;
}
Which takes in the string and stores it. I just need a way to move that second half to a new array and I know I need to use strcpy() but I don't know how to properly reference that portion of the array.
Since this is C++ I'm going to suggest a standard library algorithm. You're asking to swap two halves of a sequence and std::rotate does just that. Unfortunately it does the rotation in-place and you want the result in a different string.
You could copy the string and then do the rotation but there is a std::rotate_copy algorithm that will do both (and faster than separate copy/rotate steps).
Example with char arrays:
#include <algorithm>
#include <cstring>
#include <iostream>
int main()
{
char text[1000], result[1000];
std::cout << "Please enter a string\n";
std::cin.getline(text, 999);
size_t length = strlen(text);
std::rotate_copy(text, text + length / 2, text + length, result);
result[length] = '\0';
std::cout << text << '\n' << result << '\n';
}
Example with std::string:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string text, result;
std::cout << "Please enter a string\n";
std::getline(std::cin, text);
size_t length = text.size();
result.resize(length);
std::rotate_copy(text.begin(), text.begin() + length / 2, text.end(), result.begin());
std::cout << text << '\n' << result << '\n';
}
Demo on ideone.com
You could possibly use std::swap_ranges but that assumes both ranges are the same size.
if you are trying to use C, use strncpy. However, I recommend using C++ std::string and using the std::string.substr() and concatenation. The latter would be easier at least to me.
You were half way through the solution. Here I finished it using strncpy to get the first half and pointer incrementation to get the second one.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main(void)
{
char temp[1000];
cout << "Please enter a string" << endl;
cin.getline(temp, 999);
int length = strlen(temp);
char firstHalf[512];
strncpy (firstHalf, temp, length/2);
cout << "firstHalf: " << firstHalf << endl;
char* secondHalf = temp + length/2;
cout << "secondHalf: " << secondHalf << endl;
char* swapped_str = strcat(secondHalf, firstHalf);
cout << "Swapped string: " << swapped_str << endl;
return EXIT_SUCCESS;
}
std::string text(whatever...);
int sz = text.size() / 2;
for (int i = 0; i < sz; ++i)
std::swap(text[i], text[sz + i]);
This might be off by one when text.size() is odd.
I have the following code :
string a = "wwwwaaadexxxxxx";
Intended Output : "w4a3d1e1x6";
somewhere in my code I have int count = 1; ... count++;
Also, somewhere in my code I have to print this count as a[i] but as a number only .. like 1,2,3 and not the character equivalent of 1,2,3.
I am trying the following : printf("%c%d",a[i],count);
i also read something like :
stringstream ss;
ss << 100
What is the correct way to do so in CPP?
EDIT :
so i Modified the code to add a number at index i in a string as :
stringstream newSS;
newSS << count;
char t = newSS.str().at(0);
a[i] = t;
You can use a stringstream to concatenate the string and the count,
stringstream newSS;
newSS << a[i] << count;
and then finally convert it to string and then print it or return (if this is done inside a function)
string output = newSS.str();
cout << output << endl;
But if your objective is only to print the output, then using the printf is fine.
If you need to update in place, then you can use two pointers. Let them be i,j.
You use j to set the new value and i to count the count. This is the standard runLength Encoding Problem.
There is no "correct" way. You could use snprintf, stringstream, etc. Or you could roll your algorithm. Assuming this is a base 10 number, you want the number in base 10.
#include <iostream>
#include <string>
#include <algorithm>
int main(void)
{
int a = 1194;
int rem = 0;
std::string output;
do {
rem = a % 10;
a = a / 10;
output.append(1, rem + '0');
} while(a != 0);
std::reverse(output.begin(), output.end());
std::cout << output << std::endl;
return 0;
}
I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
string a;
cin >> a;
string b;
int c;
for(int i=0;i<a.size()-1;++i)
{
b = a.substr(i,i+1);
c = atoi(b.c_str());
cout << c << " ";
}
cout << endl;
return 0;
}
If I am correct, the second parameter of substr() should be the length of the substring. How about
b = a.substr(i,2);
?
As shown here, the second argument to substr is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.
Your line b = a.substr(i,i+1); will generate, for values of i:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
Another interesting variant question can be:
How would you make "12345" as "12 23 34 45" without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
substr(i,j) means that you start from the index i (assuming the first index to be 0) and take next j chars.
It does not mean going up to the index j.
You can get the above output using following code in c
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char *str;
clrscr();
printf("\n Enter the string");
gets(str);
for(int i=0;i<strlen(str)-1;i++)
{
for(int j=i;j<=i+1;j++)
printf("%c",str[j]);
printf("\t");
}
getch();
return 0;
}
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
The string constructor can be used to get a copy of a substring.
string(const string& str, size_t pos, size_t n)
For example...
b = string(a, i, 2); // substring of a from position i, including 2 characters
This differs from substr in that the length n cannot be omitted. I offer this only as an alternative, not as an improvement.