C++ 14我的程序没有返回预期的结果
问题描述:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//You are in the elevator now;
//Define variables;
char a;
char b;
//Ask questions;
printf("You are in the elevator now.\nPlease enter which floor you want to visit?\nPress 'L' for Basement, '1' for 1st floor, '2' for 2nd floor, and '3' for 3rd floor:\n");
scanf("%c", &a);
//Display options;
if (a=='L'){
printf("You are at the basement now.\n", a);
scanf("%c", &b);
printf("Where do you want to go?\nOnly Option is 'P' for Parking lot:\n");
else (b=='P')
printf("You are in the Parking Lot now.\n", b);
}
else if (a=='1')
printf("You are at the main floor now.\n", a);
else if (a=='2')
printf("You are at the Mechanical Department now.\n", a);
else if (a=='3')
printf("You are at the Electrical Department now.\n", a);
else{
printf("It's not an option\n");
}
}
对于用户选择P之后的第一个选项L,我得到的命令没有找到。我应该得到你现在在停车场。我不确定是什么导致了这一点。C++ 14我的程序没有返回预期的结果
答
检查这个代码了...
#include <iostream>
using namespace std;
int main()
{
//You are in the elevator now;
//Define variables;
char a;
char b;
//Ask questions;
printf("You are in the elevator now.\nPlease enter which floor you want to visit?\nPress 'L' for Basement, '1' for 1st floor, '2' for 2nd floor, and '3' for 3rd floor:\n");
scanf("%c", &a);
//Display options;
if (a=='L')
{
printf("You are at the basement now.\n");
printf("Where do you want to go?\nOnly Option is 'P' for Parking lot:\n");
cin >> b;
if (b=='P'){
printf("You are in the Parking Lot now.\n");}
}
else if (a=='1')
printf("You are at the main floor now.\n");
else if (a=='2')
printf("You are at the Mechanical Department now.\n");
else if (a=='3')
printf("You are at the Electrical Department now.\n");
else
printf("It's not an option\n");
return 0;
}
+0
@ Karthik Chowdary在用户放入L和P之后,编译器显示P命令未找到 – Wilson
答
您可能遇到的主要问题是scanf("%c")
只消耗一个字符,并且在按下输入后,缓冲区中将有一个'\n'
。你可能会想一些其他方式的输入,如使用类似:
std::string command;
std::cin >> command;
if (command == "P") {
// ...
}
因为这将在默认情况下,在一次加载整个空白 - 划定的字符串。
对不起,我多次提出问题 – Wilson
我遇到了我的电脑问题 – Wilson
为什么你不断添加随机编辑? – yizzlez