I'm trying to take a char and add it to a string. OR if that's not possible, add it to an array of characters?
I tried changed 'string updated = ""' to 'char updated[text_length]' but I was getting the same error - incompatible integer to pointer conversion error
if(argc == 2 && IsDigitsOnly(argv[argc-1])) {
// convert to integer
int x = atoi(argv[argc-1]);
// prompt user for plaintext
string plaintext = get_string("plaintext: ");
int text_length = strlen(plaintext);
int ascii = 'a';
string updated= "";
for (int i = 0; i < text_length; i )
{
if (isalpha(plaintext[i]))
{
if (isupper(plaintext[i]))
{
// GETTING ERROR HERE -- trying to pass 'letter' in strcat
// This gives me an error: incompatible integer to pointer conversion error
int n = (plaintext[i] x) % 90;
char letter = n;
strcat(updated, letter);
}
else
{
ascii = (ascii x) % 122;
}
}
}
printf("%s\n", updated);
}
CodePudding user response:
Based on the string
and get_string()
call, I assume that you are using cs50
. In this case:
You can not write to a string literal (
updated
).srtcat
wants a pointer tochar
(not achar
) as second parameter.
Switch to:
char updated[SOME_SIZE] = "";
...
char letter = n;
strcat(updated, (char[]){letter, 0});
Notice that strcat
is prone to buffer overflows, consider replacing it with snprintf
, something like:
char updated[SOME_SIZE] = "";
...
char letter = n;
size_t len = strlen(updated);
snprintf(updated len, sizeof updated - len, "%c", letter);
CodePudding user response:
How do I concat a character into a string?
// Since C99, append by forming a compound literal.
strcat(some_string, (char []){some_chracter, '\0'});
Yet in OP's case, concatenating a character to a string is a weak approach.
For this task, strcat(updated, ...)
is slow as each time a letter
needs to be appended, updated
is longer and longer. See Schlemiel the Painter's Algorithm.
A more idiomatic approach would keep track of the length of updated
and use that as an index in appending letter
.
int text_length = strlen(plaintext);
int ascii = 'a';
// string updated= "";
char updated[text_length 1]; // `text_length 1` is the maximum size needed.
// Add
int updated_used = 0;
for (int i = 0; i < text_length; i )
{
if (isalpha(plaintext[i]))
{
if (isupper(plaintext[i]))
{
int n = (plaintext[i] x) % 90;
char letter = n;
// strcat(updated, letter);
updated[updated_used ] = letter;
}
else
{
ascii = (ascii x) % 122;
}
}
}
// Add
updated[updated_used] = '\0';
Both int n = (plaintext[i] x) % 90;
and ascii = (ascii x) % 122;
look wrong.
I suspect OP wants to shift within uppercase letters with
int n = (plaintext[i] - 'A' x) % 26 'A';
and for lower case:
int n = (plaintext[i] - 'a' x) % 26 'a';