Trying to convert an char to integer - c++

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"....

Related

Trying to convert unsigned int array to unsigned char array but get a weird output

#include <iostream>
#include "cryptography.h"
#include "database.h"
#include <fstream>
#include <vector>
#include <cstring>
// Master key = 0x648821
std::string encrypt(std::string str, int key) {
for (int i = 0; i < str.length(); i++) {
str[i] += key;
}
return str;
}
std::string decrypt(std::string str, int key, int arraysize) {
for (int i = 0; i < arraysize; i++) {
str[i] -= key;
}
return str;
}
int main() {
std::vector<std::string> data = readFile("keys.txt");
unsigned char key[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
unsigned int temp[16];
for (int i = 0; i < 16; i++) {
temp[i] = stoi(decrypt(data[i], 0x648821, 16));
key[i] = temp[i];
std::cout << key[i] << std::endl;
}
}
I'm trying to get this code to output an unsigned char array of numbers used for keys in an AES128 encryption algorithm but it instead outputs a bunch of weird unicode characters (I'm using replit).
Casts your key[i] into an int to prevent char to be printed as.. a char.
std::cout << (int)key[i] << std::endl;
or in a strict c++ syntax:
std::cout << static_cast<int>(key[i]) << std::endl;
std::string encrypt(std::string str, int key) {
...
str[i] += key;
std::string is std::basic_string<char> so str[i] is a char. That can be either signed or unsigned. For signed char adding 0x648821 results in an int that then gets assigned to char causing integral conversion:
If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined (until C++20) the unique value of the destination type equal to the source value modulo 2^n.
So unless you add -std=c++20 or equivalent option you have to look up the compiler specifications of what that code means. Is that actually what you want to encrypt something?
I think it's worse in decrypt with unsigned char causing an integer underflow. But I'm too lazy to look at the integer promotion rules step by step to see if that is truly the case. So decrypt could be UB and not just IDB.
Debug your code and check that decrypt actually returns a sensible string that stoi() can understand. And then remove temp. Storing the value in an int array temporarily makes 0 difference, just assign the value to key directly.

How should I convert an increasing number array into a character array so that I can use the atoi function

#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;
}

How to count characters in a C_String in C++?

I'm a new Computer Science student, and I have a homework question that is as follows:
Write a Function that passes in a C-String and using a pointer determine the number of chars in the string.
Here is my code:
#include <iostream>
#include <string.h>
using namespace std;
const int SIZE = 40;
int function(const char* , int, int);
int main()
{
char thing[SIZE];
int chars = 0;
cout << "enter string. max " << SIZE - 1 << " characters" << endl;
cin.getline(thing, SIZE);
int y = function(thing, chars, SIZE);
cout << y;
}
int function(const char *ptr, int a, int b){
a = 0;
for (int i = 0; i < b; i++){
while (*ptr != '\0'){
a++;
}
}
return a;
}
First of all welcome to stackoverflow ye0123! I think you are trying to rewrite the strlen() function here. Try giving the following link a look Find the size of a string pointed by a pointer.
The short answer is that you can use the strlen() function to find the length of your string. The code for your function will look something like this:
int function(const char *ptr)
{
size_t length = strlen(ptr);
return length;
}
You should also only need this function and main.
Edit: Maybe I misunderstood your question and you are supposed to reinvent strlen() after all. In that case, you can do it like so:
unsigned int my_strlen(const char *p)
{
unsigned int count = 0;
while(*p != '\0')
{
count++;
p++;
}
return count;
}
Here I am comparing *p from '\0' as '\0' is the null termination character.
This was taken from https://overiq.com/c-programming-101/the-strlen-function-in-c/

Iterate over a string and fill an array in C++

I'm working on this code that iterates over a string--that is actually a string representing an integer in this case--and fills an array with each "digit" of the string. So string "350" would result in an array with elements {3,5,0}.
Here is the code:
#include <stdlib.h>
#include <iostream>
using namespace std;
int main() {
int arr[5];
string test = "10000";
for(unsigned int i = 0; i<test.length(); i++) {
char c = test[i];
cout << c << endl;
arr[i] = c;
}
//printing the array for testing
for (int i = 5 - 1; i >= 0; i--)
cout << arr[i];
return 0;
}
char c = test[i];
arr[i] = c;
}
return 0;
}
The issue is that array that results from this is {49,48,48,48,48}. I have no idea why its doing that and where I have gone wrong with the code. Why is it adding the numbers 49 and 48, and how can I fix this?
Also if it helps anyone, here is a link to a stepper running through the code:
http://pythontutor.com/visualize.html#code=%0A%23include%20%3Cstdlib.h%3E%0A%23include%20%3Ciostream%3E%0A%0A%0Ausing%20namespace%20std%3B%0A%0A%0A%0Aint%20main%28%29%20%7B%0A%20%20int%20arr%5B5%5D%3B%0A%09string%20test%20%3D%20%2210000%22%3B%0A%20%20for%28unsigned%20int%20i%20%3D%200%3B%20i%3Ctest.length%28%29%3B%20i%2B%2B%29%20%7B%0A%20%20%20%20char%20c%20%3D%20test%5Bi%5D%3B%20//this%20is%20your%20character%0A%20%20%20%20arr%5Bi%5D%20%3D%20c%3B%0A%7D%0A%09return%200%3B%0A%7D%0A%0A%0A&cumulative=false&curInstr=19&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=cpp&rawInputLstJSON=%5B%5D&textReferences=false
What you see in your array are the ascii for the characters your insert.
Here is what you should do to convert your character to an integer:
arr[i] = atoi(&c);
The 48 and 49 are your 0 and 1 in ascii. You need to convert from ascii to digits.
You created arr as an array of integers, thus by assigning character elements to it you implicitly cast them to an integer. When you do this, the ASCII value of the characters is printed, instead of the characters themselves. You should use an array of characters instead.
char arr[5];

How do you do change from one variable to another?

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
}