The conversion works correctly but when I press enter, when asked for a lower case, it executes an enter (\\n) and doesn't exit or stop.
This is my program:
#include <stdio.h>
#include <math.h>
main()
{
char ch;
printf("Press a letter: ");
while (scanf(" %c",&ch)!='\n')
{
printf("%c\n",ch-32);
}
}
Your program is incorrect:
scanf
does not return the character that has been read, it returns the number of scanned items '\\n'
is to check if (ch == '\\n') break;
toupper
function instead of using subtraction directly. use this code :
#include <stdio.h>
#include <math.h>
main()
{
char ch;
printf("Press a letter: ");
while (1)
{
scanf(" %c",&ch);
if(ch=='\n')
break;
printf("%c\n",ch-32);
}
}
scanf(" %c",&ch)
will never set ch
to \\n
as the space in the format consumes all white-space, including '\\n'
before moving on to "%c"
.
Further, the return value from scanf()
is EOF or the number of successfully parsed arguments, not ch
. (not "%n"
though)
Consider:
#include <stdio.h>
// No need for #include <math.h>
#include <ctype.h>
int main() {
int ch; // use int
printf("Press a letter: ");
while ((ch = fgetc(stdin)) != EOF && (ch != '\n')) {
printf("%c\n", toupper(ch));
}
return 0;
}
OP states in another comment "we should perform this without using outside functions, for example, my professor didn't teach us toupper". Let's assume stdio
functions are OK and ctype
ones are not.
// Assume ASCII encoding
while ((ch = fgetc(stdin)) != EOF && (ch != '\n')) {
if ((ch >= 'a') && (ch <= 'z')) {
ch += 'A' - 'a';
}
printf("%c\n", ch);
}
// Not assuming ASCII encoding, but letters a-z, A-Z
while ((ch = fgetc(stdin)) != EOF && (ch != '\n')) {
static const char *az = "abcdefghijklmnopqrstuvwxyz";
static const char *AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i;
for (i=0; az[i]; i++) {
if (ch == az[i]) {
ch = AZ[i];
break;
}
}
printf("%c\n", ch);
}
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.