I have a small C program for a college course. It is meant to encrypt
and decrypt lower case letters and leave spaces as spaces. I can't
get it to run properly as I think I have a problem in the While
construct area. It is driving me mad trying to sort it out - can
someone please help.
The program is:
/*
* Program to encrypt a message using the Turbo C random
* number generator. Only lower case letters and the space
* character can be used in the message.
*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#define SEED 1
unsigned char encrypt(unsigne d char);
unsigned char decrypt(unsigne d char);
void wait(void);
main()
{
unsigned char c;
char type;
/*
* initialise the random number generator
*/
srand(SEED);
/*
* display user headings and prompts
*/
clrscr();
cprintf("T223 encryption program\r\n\r\n ");
cprintf("Type d to decode a message or any other character to encode
");
type = getch(); /* input the user option */
cprintf("\r\nNo w type in the message, use only lower case letters "
"or space.\r\nEnd with any other character.\r\n\ r\n");
c = (unsigned char)getchar(); /* read in first character */
/*
* main encryption/decryption loop
* loop while characters are lower case letters or spaces
*/
while ((c>='a') && (c<='z') && (c=' '));
{
if (c==' ')
{
switch (type)
{
case '64':
c = decrypt (c) ;
break;
default:
c = encrypt (c) ;
break;
}
}
putchar('c'); /* display encrypted/decrypted character */
c = (unsigned char)getchar(); /* get next character */
}
/*
* end of main while loop
*/
wait();
}
/*
* end of main() function
*/
/*
* function encrypt()
* =============== ===
* encrypts a single character
*/
unsigned char encrypt(unsigne d char letter)
{
unsigned char r;
r = (unsigned char)random(26) ;
letter = letter + r;
if (letter>'z')
{
letter = letter - 26;
}
return(letter);
}
/*
* end of encrypt()
*/
/*
* function decrypt()
* =============== ===
* decrypts a single character
*/
unsigned char decrypt(unsigne d char letter)
{
unsigned char r;
r = (unsigned char)random(26) ;
letter = letter - r;
if (letter<'a')
{
letter = letter + 26;
}
return(letter);
}
/*
* end of decrypt()
*/
/*
* function wait()
* ===============
* waits for a keypress
*/
void wait(void)
{
fflush(stdin);
cprintf("\r\nPr ess return to terminate");
getchar();
}
/*
* end of wait()
*/
/*
* end of program
*/ 11 1527
Steve Clay wrote: I have a small C program for a college course. It is meant to encrypt and decrypt lower case letters and leave spaces as spaces. I can't get it to run properly as I think I have a problem in the While construct area. It is driving me mad trying to sort it out - can someone please help.
The program is:
/* * Program to encrypt a message using the Turbo C random * number generator. Only lower case letters and the space * character can be used in the message. */
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <ctype.h>
Nonstandard headers, etc. #define SEED 1
unsigned char encrypt(unsigne d char); unsigned char decrypt(unsigne d char); void wait(void);
main()
{ unsigned char c; char type;
/* * initialise the random number generator */ srand(SEED);
/* * display user headings and prompts */ clrscr(); cprintf("T223 encryption program\r\n\r\n "); cprintf("Type d to decode a message or any other character to encode "); type = getch(); /* input the user option */ cprintf("\r\nNo w type in the message, use only lower case letters " "or space.\r\nEnd with any other character.\r\n\ r\n");
Nonstandard functions, etc. c = (unsigned char)getchar(); /* read in first character */
What if getchar() returns EOF?
/* * main encryption/decryption loop * loop while characters are lower case letters or spaces */ while ((c>='a') && (c<='z') && (c=' '));
c=' ' assigns space to c, which always evaluates to nonzero (true) and
leaves c as a space.
Spurious semicolon at the end of the above statement.
{ if (c==' ') { switch (type) { case '64':
'64' is two characters in a single character literal; it's
implementation defined what this means. Why not just use 'd'?
c = decrypt (c) ; break;
default: c = encrypt (c) ; break; } } putchar('c'); /* display encrypted/decrypted character */
You mean putchar(c);
c = (unsigned char)getchar(); /* get next character */ } /* * end of main while loop */ wait(); }
/* * end of main() function */
/* * function encrypt() * =============== === * encrypts a single character */ unsigned char encrypt(unsigne d char letter) { unsigned char r; r = (unsigned char)random(26) ; letter = letter + r; if (letter>'z') { letter = letter - 26; } return(letter); } /* * end of encrypt() */
/* * function decrypt() * =============== === * decrypts a single character */ unsigned char decrypt(unsigne d char letter) { unsigned char r; r = (unsigned char)random(26) ;
You mean rand().
letter = letter - r; if (letter<'a') { letter = letter + 26; } return(letter); } /* * end of decrypt() */
/* * function wait() * =============== * waits for a keypress */
void wait(void) { fflush(stdin);
Undefined behavior here.
cprintf("\r\nPr ess return to terminate"); getchar(); } /* * end of wait() */
/* * end of program */
--
Pull out a splinter to reply.
Hi Steve,
Peter already pointed out some problems
in your program (more I ever found). I
just want to add s.th. according your
while condition: while ((c>='a') && (c<='z') && (c=' '));
Isn't it
while ((c>='a') && (c<='z') || (c==' '))
a character 'or' space?
Regards
Michael
Michael wrote: Hi Steve, Peter already pointed out some problems in your program (more I ever found). I just want to add s.th. according your while condition:
while ((c>='a') && (c<='z') && (c=' '));
Isn't it
> while ((c>='a') && (c<='z') || (c==' ')) a character 'or' space?
Well, that's certainly an improvement, since no character can be a letter
/and/ a space. But this:
while(islower(( unsigned char)c) || (c == ' '))
is better still, since it doesn't rely on lower case letters being
contiguous and in alphabetical order.
--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Richard Heathfield wrote: Michael wrote:
Hi Steve, Peter already pointed out some problems in your program (more I ever found). I just want to add s.th. according your while condition:
while ((c>='a') && (c<='z') && (c=' '));
Isn't it
> while ((c>='a') && (c<='z') || (c==' ')) a character 'or' space?
Well, that's certainly an improvement, since no character can be a letter /and/ a space. But this:
while(islower(( unsigned char)c) || (c == ' '))
is better still, since it doesn't rely on lower case letters being contiguous and in alphabetical order.
How would you write islower in C,
if you didn't care about the consequences of undefined behavior ?
I've got this:
#include <limits.h>
#include <string.h>
#define LOWER "abcdefghijklmn opqrstuvwxyz"
int islower(int c)
{
return CHAR_MAX >= c && c > '\0' && strchr(LOWER, c) != NULL;
}
In <40***********@ mindspring.com> pete <pf*****@mindsp ring.com> writes: How would you write islower in C, if you didn't care about the consequences of undefined behavior ?
I've got this:
#include <limits.h> #include <string.h>
#define LOWER "abcdefghijklmn opqrstuvwxyz"
int islower(int c) { return CHAR_MAX >= c && c > '\0' && strchr(LOWER, c) != NULL; }
The idea is that some programs make intensive use of the <ctype.h> stuff,
so you want them to be as fast as possible. They're usually implemented
using a lookup table defining a number of attributes (as binary flags)
for each character. Each function simply gets the flags value associated
with the corresponding character and ANDs it with a mask preserving only
the relevant bit(s).
A change of locale simply means using another lookup table. OTOH,
<wctype.h> stuff may need to be handled differently...
Have a look at Plauger's book.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Below is a program taken from a book that does the same thing
you are trying to do hope it helps!
/* Program: Coder.c
* Usage: Coder [filename] [action]
* where filename = filename for/with coded data
* where action = D for decode anything else for
* coding
*--------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int encode_characte r( int ch, int val );
int decode_characte r( int ch, int val );
int main( int argc, char *argv[])
{
FILE *fh; /* file handle */
int rv = 1; /* return value */
int ch = 0; /* variable to hold a character */
unsigned int ctr = 0; /* counter */
int val = 5; /* value to code with */
char buffer[256]; /* buffer */
if( argc != 3 )
{
printf("\nError : Wrong number of parameters..." );
printf("\n\nUsa ge:\n %s filename action", argv[0]);
printf("\n\n Where:");
printf("\n filename = name of file to code or decode");
printf("\n action = D for decode or C for encode\n\n");
rv = -1; /* set return error value */
}
else
if(( argv[2][0] == 'D') || (argv [2][0] == 'd' )) /* to decode */
{
fh = fopen(argv[1], "r"); /* open the file */
if( fh <= 0 ) /* check for error */
{
printf( "\n\nError opening file..." );
rv = -2; /* set return error value */
}
else
{
ch = getc( fh ); /* get a character */
while( !feof( fh ) ) /* check for end of file */
{
ch = decode_characte r( ch, val );
putchar(ch); /* write the character to screen */
ch = getc( fh);
}
fclose(fh);
printf( "\n\nFile decoded to screen.\n" );
}
}
else /* assume coding to file. */
{
fh = fopen(argv[1], "w");
if( fh <= 0 )
{
printf( "\n\nError creating file..." );
rv = -3; /* set return value */
}
else
{
printf("\n\nEnt er text to be coded. ");
printf("Enter a blank line to end.\n\n");
while( fgets(buffer, 256, stdin) != NULL )
{
if( strlen (buffer) <= 1 )
break;
for( ctr = 0; ctr < strlen(buffer); ctr++ )
{
ch = encode_characte r( buffer[ctr], val );
ch = fputc(ch, fh); /* write the character to file */
}
}
printf( "\n\nFile encoded to file.\n" );
fclose(fh);
}
}
return rv;
}
int encode_characte r( int ch, int val )
{
ch = ch + val;
return ch;
}
int decode_characte r( int ch, int val )
{
ch = ch - val;
return ch;
}
On Wed, 25 Feb 2004 14:01:38 UTC, pete <pf*****@mindsp ring.com> wrote: I've got this:
#include <limits.h> #include <string.h>
#define LOWER "abcdefghijklmn opqrstuvwxyz"
int islower(int c) { return CHAR_MAX >= c && c > '\0' && strchr(LOWER, c) != NULL; }
try to test the strings
"MÄHMASCHIN E"
"mähen"
"büßen"
.......
fails miserably on characters used by french, italian, german,
norways, .........
The world is not US only.
islower() works correctly on them when LC_LOCALE is set correctly.
--
Tschau/Bye
Herbert
Visit http://www.ecomstation.de the home of german eComStation
The Real OS/2 Guy wrote: On Wed, 25 Feb 2004 14:01:38 UTC, pete <pf*****@mindsp ring.com> wrote:
I've got this:
#include <limits.h> #include <string.h>
#define LOWER "abcdefghijklmn opqrstuvwxyz"
int islower(int c) { return CHAR_MAX >= c && c > '\0' && strchr(LOWER, c) != NULL; }
try to test the strings
"MÄHMASCHIN E" "mähen" "büßen" ......
fails miserably on characters used by french, italian, german, norways, ......... The world is not US only.
islower() works correctly on them when LC_LOCALE is set correctly.
I don't have LC_LOCALE in my version of N869.
Is it possible for a conforming implementation to only support
the "C" locale ?
--
pete
Dan Pop wrote: In <40***********@ mindspring.com> pete <pf*****@mindsp ring.com> writes:
How would you write islower in C, if you didn't care about the consequences of undefined behavior ?
I've got this:
#include <limits.h> #include <string.h>
#define LOWER "abcdefghijklmn opqrstuvwxyz"
int islower(int c) { return CHAR_MAX >= c && c > '\0' && strchr(LOWER, c) != NULL; }
The idea is that some programs make intensive use of the <ctype.h> stuff, so you want them to be as fast as possible.
I'm interested in simple portable ways of expressing
standard library functions, minimally, for academic reasons.
--
pete This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Kurt Watson |
last post by:
I’m having a different kind of problem with Hotmail when I sign in it
says, "Web Browser Software Limitations
Your Current Software Will Limit Your Ability to Use Hotmail
You are using a web browser that Hotmail does not support. If you
continue to use your current browser software we cannot guarantee that
Hotmail will work correctly for you".
Please help, this is very annoying. I have been searching for help on
|
by: x muzuo |
last post by:
Hi guys,
I have got a prob of javascript form validation which just doesnt work
with my ASP code. Can any one help me out please.
Here is the code:
{////<<head>
<title>IIBO Submit Page</title>
</head>
<style type="text/css">
|
by: tyler_durden |
last post by:
thanks a lot for all your help..I'm really appreciated...
with all the help I've been getting in forums I've been able to continue
my program and it's almost done, but I'm having a big problem that I
believe if it's solved, the remaining stuff is easy...
my full program until now is here:
http://www.geocities.com/tom4_h4wk/progmail.zip
the problem is the segmentation fault when main trys to run
leficheiro.c.... the *.c2 files are the...
|
by: Jason |
last post by:
Hi,
I was wondering if any could point me to an example or give me ideas on how
to dynamically create a form based on a database table? So, I would have a
table designed to tell my application to create certain textboxes, labels,
and combo boxes? Any ideas would be appreciated.
Thanks
|
by: Joner |
last post by:
Hello,
I'm having trouble with a little programme of mine where I connect to
an access database. It seems to connect fine, and disconnect fine, but
then after it won't reconnect, I get the error "operation is not
allowed when object is open" so I take out the line of code:
BookDetails.Connection1.Open
and it comes up with the error "operation is not allowed when object
| |
by: David Van D |
last post by:
Hi there,
A few weeks until I begin my journey towards a degree in Computer
Science at Canterbury University in New Zealand,
Anyway the course tutors are going to be teaching us JAVA wth bluej and
I was wondering if anyone here would be able to give me some tips for
young players such as myself, for learning the language.
Is this the best Newsgroup for support with JAVA?
|
by: PEB |
last post by:
POSTING GUIDELINES
Please follow these guidelines when posting questions
Post your question in a relevant forum
Do NOT PM questions to individual experts - This is not fair on them and we instruct our experts to ignore any such PMs completely
Be sure to give the version of Access that you are working with and the Platform and OS if applicable.
|
by: 2Barter.net |
last post by:
newsmail@reuters.uk.ed10.net Fwd: Money for New Orleans, AL & GA
Inbox
Reply
Reply to all
Forward
Print
Add 2Barter.net to Contacts list
Delete this message
Report phishing
Show original
|
by: jenipriya |
last post by:
Hi all... its very urgent.. please........i m a beginner in oracle.... Anyone please help me wit dese codes i hv tried... and correct the errors...
The table structures i hav
Employee (EmpID, EmpName,DeptID,DateOfJoin, Sal, Addr)
Finance (EmpID, Sal)
Club (Clubname, EmpID, Fee, DateOfJoin)
Leave (EmpID, Date)
Department (DeptID, DeptName, NoOfEmployees)...
|
by: tabani |
last post by:
I wrote the program and its not giving me correct answer can any one help me with that please and specify my mistake please it will be highly appreciable...
The error arrives from option 'a' it asks for user name, check in the system but does not return the correct answer please help me with it.
or if you have better way of doing it would you please mind to tell me..
thanks..
#!/usr/bin/perl -w
#use Getopt::Std;
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |