从键盘输入“12”,执行#include<stdio.h> void main() { int c; while((c=getchar())!='\n'); switch(c) { case'0'; case'1':putchar(c+1); case'2':putchar(c+1);break; case'3':putchar(c+2); default:putchar(c+2);break; } }代码,输出结果是什么,为什么?
时间: 2024-04-21 19:25:06 浏览: 19
从键盘输入 "12",程序会读入字符 '1' 和 '2',但是由于代码中的 while 循环将会读入并丢弃所有的输入字符,直到读入一个换行符为止。因此,在 switch 语句中,只有最后一个输入的字符 '2' 会被处理。
根据代码中的 switch 语句,字符 '2' 会匹配 case '2',然后输出字符 '3',因为 '2' 的 ASCII 码是 50,加上 1 后变成 51,对应的字符是 '3'。由于代码中加了 break 语句,程序会跳出 switch 语句,然后输出字符 '3',因为 '2' 的 ASCII 码是 50,加上 2 后变成 52,对应的字符是 '4'。
因此,程序的输出结果是 "34"。
相关问题
C++编制一个读单词过程,以#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #define NULL 0为开头
C++编写一个读取单词的过程可以以下代码:
```cpp
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define NULL 0
void readWord(char* word) {
int index = 0;
char ch;
// 跳过空白字符
while ((ch = getchar()) != EOF && isspace(ch));
// 读取单词字符
while (ch != EOF && !isspace(ch)) {
word[index++] = ch;
ch = getchar();
}
// 添加字符串结束符
word[index] = '\0';
}
int main() {
char word[100];
readWord(word);
printf("读取的单词是:%s\n", word);
return 0;
}
```
上述代码中,`readWord`函数用于读取一个单词,它会跳过输入中的空白字符,然后读取连续的非空白字符作为一个单词。`main`函数中调用了`readWord`函数,并打印出读取到的单词。
Nirvana 15:38:49 #include <stdio.h> #include <conio.h> #include <stdbool.h> #define MAX_QUEUE_SIZE 1000 void main() { char queue[MAX_QUEUE_SIZE]; int front=0,rear=0; char ch; ch=getchar(); while(ch!='#') { queue[rear]=ch; rear++; ch=getchar(); } while(front<rear) { printf("%c",queue[front]); front++; } printf("\n"); getch(); } Nirvana 15:39:07 #include <stdio.h>#include <conio.h>#define MAX_STACK_MAX 1000void main(){ char stack[MAX_STACK_MAX]; int top=0,i; char ch;ch=getchar(); while (ch!='!'&&top<MAX_STACK_MAX) { switch(ch) { case'#': if(top>0) top--; break; case'@': top=0; break; default: stack[top]=ch; top++; break; } ch=getchar(); } for(i=0;i<top;i++) printf("%c",stack[i]); printf("\n"); getch();}将这两段代码合为一段代码
以下是将两段代码合并后的代码:
```c
#include <stdio.h>
#include <conio.h>
#include <stdbool.h>
#define MAX_QUEUE_SIZE 1000
#define MAX_STACK_MAX 1000
void main() {
char queue[MAX_QUEUE_SIZE];
int front = 0, rear = 0;
char stack[MAX_STACK_MAX];
int top = 0, i;
char ch;
ch = getchar();
while (ch != '#') {
queue[rear] = ch;
rear++;
ch = getchar();
}
ch = getchar();
while (ch != '!' && top < MAX_STACK_MAX) {
switch(ch) {
case '#':
if (top > 0) {
top--;
}
break;
case '@':
top = 0;
break;
default:
stack[top] = ch;
top++;
break;
}
ch = getchar();
}
printf("Queue output: ");
while (front < rear) {
printf("%c", queue[front]);
front++;
}
printf("\n");
printf("Stack output: ");
for (i = 0; i < top; i++) {
printf("%c", stack[i]);
}
printf("\n");
getch();
}
```
这个合并后的代码可以分别读入字符到队列和栈中,并输出它们的内容。其中,遇到 `#` 时队列弹出元素,遇到 `@` 时栈清空。