Implements case conversion of letters. Multiple sets of input and output
example
A
B
a
b
Table of contents
getchar()
#include<stdio.h>
int main()
{
int ch = 0;
while (ch = getchar())
{
putchar(ch+32);
}
return 0;
}
Because
From the keyboard, type A and enter (\n) to the buffer, getchar first takes A from the buffer (A+32 corresponds to a in the ASCII table), and takes \n from the buffer (\n+ 32 corresponds to *) in the ASCII table
So the output is: a*
Solution:
Use another getchar() to read the carriage return
int main()
{
int ch = 0;
// EOF: end of file
//想让循环停止:Ctrl+Z
while ((ch = getchar()) != EOF)
{
putchar(ch+32);
getchar();//用来读取\n
printf("\n"); //换行
}
return 0;
}
Improve
#include<stdio.h>
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
{
printf("%c\n",ch+32);
getchar();//用来读取\n
}
return 0;
}
scanf()
#include <stdio.h>
int main() {
char ch = 0;
while(scanf("%c ",&ch) != EOF)
{
printf("%c\n",ch+32);
}
return 0;
}
Regarding ~scanf() for multiple sets of input in a while loop
#include <stdio.h>
int main() {
char ch = 0;
while(~scanf("%c ",&ch))
{
printf("%c\n",ch+32);
}
return 0;
}
EOF
EOF goes to the definition in C language and its value is (-1), end of file, the end of the file.
EOF is returned by an I/O routine when the end-of-file (or in some cases, an error) is encountered.
Meaning: when end-of-file (or in some cases, error) is encountered, the I/O process returns EOF.
When performing multiple sets of input in the terminal, press Ctrl+Z to stop the input.
- ~ This is a c language operator, bitwise negation.
Both while(scanf("%c",&ch) != EOF) and while(~scanf("%c",&ch)) can perform multiple sets of input and output.