I'm trying to add "Encrypted message: "
before the encrypted message is printed.
When I put the printf
statement inside the "while" loop, I get something along the lines of: AEncrypred message: BEncrypted message: CEncrypted message:
etc.
If I try and put the printf
statement outside the loop, nothing prints.
Is there a way to print "Encrypted message: "
before the result while still using putchar();
?
#include <stdio.h>
#include <ctype.h>
char encrypt(char in, int key)
{
if (isalpha(in))
{
if (isupper(in))
{
return (((in-'A') + key) % 26) + 'A';
}
else
{
return (((in-'a') + key) % 26) + 'a';
}
}
else return in;
}
int main()
{
int key;
char ch, res;
printf("Enter shift amount (1-25):\n");
scanf("%d", &key);
printf("Enter message to be encrypted:\n");
getchar();
while (ch != '\n')
{
ch = getchar();
res = encrypt(ch, key);
putchar(res);
}
return 0;
}
#include <stdio.h>
#include <ctype.h>
char encrypt(char in, int key)
{
if (isalpha(in))
{
if (isupper(in))
{
return (((in-'A') + key) % 26) + 'A';
}
else
{
return (((in-'a') + key) % 26) + 'a';
}
}
else return in;
}
int main()
{
int key;
char ch, res;
int checksum = 1;
printf("Enter shift amount (1-25):\n");
scanf("%d", &key);
printf("Enter message to be encrypted:\n");
getchar();
while (ch != '\n')
{
ch = getchar();
res = encrypt(ch, key);
if(checksum) { checksum = 0; printf("Encrypted message: "); }
putchar(res);
}
return 0;
}
I would use that way. If you don't like it.. let me know. I just solved it on a way that won't violate your code structure.
Your problem is putting the printf
statement inside a loop. The loop will parse your printf
statelement ? times , until ch
equals new line. To prevent that you can use a variable outside the scope, initialized with a value for example 1
. To parse the printf
statement once you do a condition if that variable equals its number and then assign 0 or another number to it. So in the next time the printf
has to be parsed, it won't go, because the condition will be false.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.