I have a few questions:
How do you get a certain char from a string?
How do you get a char to a int?
How do you get a int to a char?
How do you append a char to a string?
I was just making a simple keyed cipher... just playing around to learn cpp. I do know java so if you could relate to that it would be great!
Here is my code so please tell me how to improve... thanks! :)
#include <string>
using namespace std;
string encrypt(string data, string pass) {
// Use a Keyed Cipher //
string encrypted;
int index = 0;
for (int x = 0; x < sizeof(data); x++) {
int tmp = static_cast<int>(data.substr(x));
int tmpPass = static_cast<int>(pass.substr(index));
tmp += tmpPass;
if (tmp > 126) {
tmp -= 95;
}
if (index > sizeof(pass)) {
index = 0;
}
encrypted += static_cast<char>(tmp);
}
return data;
}
How do you get a certain char from a string?
By using index operator. string::operator[]
How do you get a char to a int?
int charToInteger = stringName[i] ;
How do you append a char to a string?
Using string::append
From the link -
string& append ( size_t n, char c );
Appends a string formed by the repetition n times of character c.
First of all with a string: const char& operator[] ( size_t pos ) const; e.g.:
char tmp = encrypted[x];
For conversion, you can just use C-style conversions:
int tmp = (int)encrypted[x];
This should generally work, as long as you're using an architecture with sizeof(char) <= sizeof(int) (e.g. some Texas Instruments calculators :)
But, in your code, you can just operate with chars, because chars can also be used as numeric types.
The easiest way to append a char to string is using += :
string s = "Hello worl";
s += 'd';
How do you get a certain char from a string?
the class "string" implements the operator [], so to get the "i" char you can use mystring[i].
std::string has a function called "c_str()" which returns "const char*" that is inside the string.
so another way to get a char from a std::string is *(mystring.c_str()+i).
How do you get a char to a int?
char is a 1 byte data type, so you can cast char into an int just like in java.
char c = 'a';
int i = (int)c;
How do you get a int to a char?
just like in Java. notice that int is usually 4 bytes (doesn't have to be 4 bytes!!!), so you might lose data because char is 1 byte.
int i=0xFFFF
char c = (char)i;
c is 0xFF! lost some data!
How do you append a char to a string?
std::string implements operator += so you can use it.
string s = "foo"; char c=s[1];
char c = 'a'; int i = c;
int i = 65; char c = (char) i;
string s = "foo"; char c = 'X'; s += c;
for (int x = 0; x < sizeof(data); x++) won't work - use data.size() not sizeof(data)
int tmp = static_cast<int>(data.substr(x)); won't work either. If you want the ascii value of data[x] just do int tmp = data[x];
if (index > sizeof(pass)) won't work - you need to use pass.size()
And finally, you never increase index within the loop, and you return the wrong string.
#include <string>
using namespace std;
string encrypt(string const & data, string const & pass) { // Pass arguments by const reference, not as values which are copied
// Use a Keyed Cipher //
string encrypted;
int index = 0;
for (int x = 0; x < data.size(); ++x) { // Loop over the length of the string, not the size of the string object
int tmp = data[x]; // No need to cast
int tmpPass = pass[index]; // No need to cast
tmp += tmpPass;
if (tmp > 126) {
tmp -= 95;
}
++index; // Remember to loop over the password as well
if (index >= pass.size()) { // Check against length of string, not size of object
index = 0;
}
encrypted += static_cast<char>(tmp);
}
return encrypted; // Return the encrypted string
}
Related
#include<stdio.h>
#include <string>
#include <stdint.h>
#include<sstream>
#include <stdlib.h>
using namespace std;
string IntToString(int&);
int main()
{
char output[45] = "0";
int str = 0;
char enc[8] = "0";
int enc1[1] = { 0 };
int arrayLength = sizeof(enc1) / sizeof(enc1[0]);
string strs;
for (int i = 0; i <= 100000; i++)
{
int enc1[1];
enc1[0]={ i };
for (int i = 0; i < arrayLength; i++)
{
int& temp = enc1[i];
strs+= IntToString(temp);
enc == strs.c_str();
}
if (atoi(enc)+46*2 == 3251)
{
output == enc;
}
}
printf("%s", output);
}
string IntToString(int& i)
{
string s;
stringstream ss(s);
ss << i;
return ss.str();
}
This is what I want to convert an integer array into a string by continuously increasing, and then convert the string into a number according to the atoi function as a function,I've looked at tutorials on using stoi and I'm not sure what I'm doing wrong. I would appreciate it if you could help me
You code has a lot of problems...
As for your question, if you want to convert an integer into a string, just use std::string your_string = std::to_string(you_integer);.
Then some of the problems that you have:
enc == strs.c_str(); <- the operator == is not the assignment operator. What you do here is that you compare two pointers, that is probably not what you intended, because you don't even check the result of the comparison.
Don't use the loop index i in a nested loop when it is already in use.
Don't use char arrays in C++ unless you have an explicit reason to use it. Even if you are worried about performance, for small strings you can look at std::string as a char array. And you cannot have large strings, because the largest possible integer value represented as a string still counts as a small string.
If you have arrays with constant size, use #define ARRAY_SIZE 15 or something like this rather than what you did.
Don't pass primitive types by reference if you don't have to. As far as I know, only double and long long are larger (on most platforms) than a reference, so you won't gain anything from passing by reference. On the contrary, the optimizer won't like you if you use unnecessary aliasing.
I have to say, I am not sure that I understood your goal correctly. But as I understood it, you want to convert an integer array into a string then to an integer. I am not quiet sure why you would want to do that, but that's on me.
The following code does what I think you wanted. It converts an integer array into an integer by first converting it into a string. But even so, you cannot increase the array size much, because std::stoi will throw an std::out_of_range exception when the number in the string would be too large for an integer.
#include <string>
#include <iostream>
#define ARRAY_SIZE 9
int int_arr_to_int (const int * const arr) {
std::string str;
for (size_t i = 0; i < ARRAY_SIZE; ++i) {
str += std::to_string(i);
}
return std::stoi(str);
}
int main(int argc, char* argv[]) {
int arr[15] = { 0 };
for (size_t i = 0; i < ARRAY_SIZE; ++i) {
arr[i] = i;
}
std::cout << int_arr_to_int(arr) << std::endl;
return 0;
}
I am trying to reverse a char which has been provided in input from an user. I am having issues with the reverse function, particularly the loop. I can't get it to work- can I get advice?
#include <iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char temp[len];
for(int i=len; i>len; --i) {
temp[i]+=input[i];
}
return temp;
}
int main()
{
char input[100];
while(cin>>input) {
cout << reverse(input);
}
return 0;
}
Your Program has few issues
You're trying to return local variable address i.e. temp array address. The Function will return the address to main function. Since memory might get cleaned so it will print garbage value present at the address.
As Rohan Bari mentioned variable length array might cause undefined behavior. There for you can create a constant length array i.e.
char temp[100];
or you can dynamically allocate array on heap. Memory allocated on heap do not get cleared after termination of block but we have to manually delete it.
char* temp = new char[len];
As array start from 0 it goes till len-1 so loop condition should start from len-1 and has to go till 0 to reverse.
+ operator do not work's with array or char even if you are trying to add just char it preforms normal integer addition of their ASCII value.
Here is improved version of your code
#include<iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char* temp = new char [len]; // or you can use char temp[100];
int j = 0; //temp variable to enter values from 0th index if we use same as loop it just enter in the same order as original char array.
for(int i=len-1; i>=0; --i) {
temp[j++] = input[i];
}
temp[j] = '\0';
return temp;
}
You have got several errors in the program.
The variable-length arrays are used here:
char temp[len];
This should not be applied in C++ since this invokes undefined-behavior. Note that this is a valid statement in the C99 standard.
There is a better alternative to this. That is to take the std::string built-in type in use.
In the following line:
temp[i] += input[i];
You are not sequentially adding one character after another, but the values of them in a single integer. This could be not a problem if temp was of the type std::string.
The reverse function should look like this:
const char *reverse(char *input) {
int len = strlen(input);
std::string temp;
while (len--)
temp += input[len];
return temp.c_str();
}
len should actually be (len-1) and i should be >= 0 not len, so from (len-1) to 0 your loop should run.
for(int i = len-1; i >= 0; i--){}
You have to allocate the new array with the new keyword if you don't want to use a string. The following code does what you need:
char* reverse(char* input)
{
int len = strlen(input);
char* temp = new char[len + 1];
for (int i = len; i >= 0; --i)
{
temp[len-i-1] = input[i];
}
temp[len] = '\0';
return temp;
}
You could use a std::stack to reverse your input:
std::stack<char> s;
char c;
while (std::cin >> c)
{
s.push(c);
}
while (!s.empty())
{
std::cout << s.top();
s.pop();
}
It's 2021. Use the STL. If your instructor isn't aware of it or doesn't allow you to use it, your instructor is not keeping up-to-date and you should fire your instructor.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string input{};
while(std::getline(std::cin, input)) {
std::reverse(std::begin(input), std::end(input));
std::cout << input << '\n';
}
return 0;
}
There's quite many things wrong with the code as many people have already mentioned! Since you want to implement this without using STL it can be done this way,
#include <iostream>
using namespace std;
#include <cstring>
void reverse(char* input,int len) { //added len as argument
char temp[len];
for(int i=len-1; i>=0; --i) {
temp[len-i-1]=input[i];
cout<<temp[len-i-1]; //printing while reversing
}
cout<<endl;
}
int main()
{
char input[100];
int len=0;
//using do while since it has to run atleast once
do{
cin.getline(input,100);
len=strlen(input);
input[len]='\0';
if(len!=0)
reverse(input,len);
}while(len!=0) ;
return 0;
}
I have no idea how to cast str[str.size()-2] and str[str.size()-1] as integers. I need to return answers as integers.
int main()
{
cin>>D;
int k;
int z;
int*tab=new int [D];
for (int i=0;i<D;i++)
{
cin>>tab[i];
}
for (int i=0;i<D;i++)
{
z=silnia(tab[i]);
string str = to_string(z);
if (str.size()>1)
cout<<str[str.size()-2]<<" "<<str[str.size()-1];
else
cout<<"0 "<<str[0];
cout<<endl;
suma=1;
}
return 0;
}
I think you can use substr and atoi.
string std::string::substr (size_t pos = 0, size_t len = npos) const;
Generate substring
Returns a newly constructed string object with its value initialized to a copy of a substring of this object. The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).
http://www.cplusplus.com/reference/string/string/substr/
int atoi (const char * str);
Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.
http://www.cplusplus.com/reference/cstdlib/atoi/
you can include sstream library then simply do the following:
stringstream a(str[str.size()-2]);
int x;
a >> x;
now x has the value of whatever ur string was and you can freely return x
I'm having trouble trying to come up with the pointer version of this function:
void strncpy(char t[], const char s[], const unsigned int n)
{
unsigned int i = 0;
for(i = 0; i < n and s[i]; i++)
t[i]=s[i];
t[i] = '\0'
}
This function is supposed to copy the first "n" characters of one array to another array and then terminate with a null character. I'm sure this is simple but I'm still learning pointers :P
This is what I have right now:
void strncpy(char * t, const char * s, const unsigned int * n)
{
unsigned int i = 0;
for(i = 0; i < *n and *s; i++)
*t = *s;
*t = '\0';
}
Im calling it in main via:
char array_one[5] = "quiz";
char array_two[5] = "test";
unsigned int x = 2;
strncpy(array_one,array_two,x);
You've failed to increment the pointers, so you're always overwriting the same address. There's also no need to pass n via a pointer:
#include <cstddef>
void my_strncpy(char *t, const char *s, std::size_t n) {
while (n && *s) {
*t++ = *s++;
--n;
}
*t = '\0';
}
NB: note use of size_t to duplicate the standard parameter signature
of the standard strncpy function, although the standard version also returns the original value of t rather than void.
#include <iostream>
// changing the function signature to take an int instead of
// pointer to int - cleaner
void my_strncpy(char * t, const char * s, const unsigned int n)
{
unsigned int i = 0;
for(i = 0; i < n; i++)
{
*t++ = *s++; // copy and increment
}
*t = '\0'; // fixing - added terminating char
}
int main(void)
{
char a[] = "string1";
char b[] = "string2";
my_strncpy(a,b,7); // replace 7 with appropriate size
std::cout << a << std::endl;
}
You need to copy over each character from one string to another and then increment the pointers - you were missing that in your implementation.
I also assume that you will not overshoot the array you are copying from.
So i'm trying to produce the sum of the variable date of type char in the following code using the atoi() function. But when doing so it returns this error message: test.cpp:9:25: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] and i can't seem to figure out what the problem is, help would be greatly appriciated.
#include <iostream>
using namespace std;
int calcNumber(const char* date, const int arraySize)
{
int sum(0);
for (int count=0; count<arraySize; count++) {
sum += atoi(date[count]);
}
return sum;
}
int main()
{
char date[] = "131083";
cout << calcNumber(date, sizeof(date) / sizeof(date[0]));
}
The std::atoi function expects a const char* type. When dereferencing a pointer of type const char* with the [] operator you are supplying the char type. That being said what you need there is the std::strlen function to determine the length of your character array -1 to address the \0 null terminating character and your count <= arraySize condition:
#include <iostream>
int calcNumber(const char* date, const size_t arraySize) {
int sum = 0;
for (int count = 0; count <= arraySize; count++) {
sum += date[count] - '0';
}
return sum;
}
int main() {
const char* p = "1234";
std::cout << calcNumber(p, strlen(p) - 1);
}
date[count] is a single char, perhaps '3' (that is ASCII code 51, so it is the same as (char)51).
To convert that into a small number (e.g. 3), use date[count]-'0'
(of course '0' is also a char constant literal, its value is 48 in ASCII; and the ASCII encoding is such that digits glyphs are encoded by consecutive codes).
BTW, you want to stop on a zero byte (terminating every string). So you could use
for (int count=0; date[count] != (char)0; count++) {
sum += atoi(date[count]);
}
then you don't even need to pass any arraySize.
Actually, you are re-inventing (poorly) std::atoi (or strtol). Your calcNumber would handle incorrectly strings like "2X" (but std::atoi("2X") gives 2 which makes more sense). And your calcNumber also behaves badly on "-34" or on " 1"....