I'm having a problem with atoi()
in the only_digits
function. I asked on discord and they said that I am passing a char type arg to atoi()
which doesn't work since atoi()
only takes string or char * (array of char) as arguments. I don't get it. I'm confused with the difference of string and char. Aren't I passing argv[1]
(which is a string) to only_digits
? Which means inputKey
is a string as well? So what do they mean that I am passing a char type arg to atoi()
? How exactly do I make atoi()
work? I'm stuck with this problem for 2 days now.
// Encrypts text using Caesar's cipher
// ci = (pi k) % 26
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
bool only_digits (string inputKey);
char rotate (char plaintext[], int key);
int main(int argc, string argv[])
{
string p;
// Make sure program was run with just one command-line argument
if (argc != 2)
{
printf("Enter exactly one input\n");
return 1;
}
// Make sure every character in argv[1] is a digit (DOESN'T WORK)
/*else if (only_digits(argv[1]))
{
printf("Usage: ./caesar key\n");
return 1;
}*/
else
{
p = get_string("plaintext: ");
}
// Convert argv[1] from a string to an int
int k = atoi(argv[1]);
char c[strlen(p) 1];
// Convert ASCII range down to a value from 0 to 25
// For each character in the plaintext: (DOESN'T WORK)
for (int i = 0, n = strlen(p); i <= n; i )
{
// Rotate the character if it's a letter // ci = (pi k) % 26
if (isalpha(p[i]))
{
if (isupper(p[i]))
{
c[i] = ((p[i]) k) % 26;
}
else if (islower(p[i]))
{
c[i] = ((p[i]) k) % 26;
}
}
}
printf("ciphertext: %s\n", c);
}
// Function to encrypt plaintext
/*char rotate (char plaintext[], int key)
{
char c[strlen(plaintext) 1];
return c;
}*/
// Function to check if key is a digit (DOESN'T WORK)
bool only_digits (string inputKey)
{
int flag = 0;
for (int i = 0, n = strlen(inputKey); i < n; i )
{
// Converts string input to int
int response = atoi(inputKey[i]);
// Check if it is a digit
if (!(isdigit(response)))
{
flag ;
}
}
if (flag != 0)
{
return false;
}
else
{
return true;
}
}
CodePudding user response:
Strings in C are defined as a sequence of nonzero bytes (characters), followed by a null-terminating byte:
char str[] = "hello"; /* in memory: { 'h', 'e', 'l', 'l', 'o', '\0' } */
atoi
(ASCII to integer) expects a proper null-terminated string (char *
). You can not pass it a single char
.
int number = atoi("1672387");
isdigit
expects a single character.
int is_true = isdigit('5');
In your program inputKey[i]
is a single character. You can test it directly with isdigit
, there is no need to convert it to an integer representation beforehand.
You can also simply return early if you encounter a non-digit character.
bool only_digits(string inputKey) {
for (size_t i = 0, length = strlen(inputKey); i < length; i )
if (!isdigit(inputKey[i]))
return false;
return true;
}
Note: size_t
is the return type of strlen
, and the most appropriate type for indexing memory.