C++ C++;必须输入两次
我正在使用Visual Studio Professional 2013。 当运行简单的代码时,如:C++ C++;必须输入两次,c++,visual-studio,input,C++,Visual Studio,Input,我正在使用Visual Studio Professional 2013。 当运行简单的代码时,如: #include "stdafx.h" #include <iostream> #include <string> using namespace std; int _tmain() { int choice; double fahr, cel; cout << "Please choose 1 for Fahrenheit, or 2 for
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain()
{
int choice;
double fahr, cel;
cout << "Please choose 1 for Fahrenheit, or 2 for Celsius conversion: ";
if (cin >> choice) {
while (cin >> choice){
if (choice == 1)
{
cout << "Enter Fahrenheit degrees to be converted: ";
cin >> fahr;
cel = (fahr - 32.0) / 1.8;
cout << fahr << " degrees Fahrenheit is " << cel << " degrees Celsius" << endl;
cout << "Please type a character followed by Enter, to end the program";
int stop; cin >> stop;
return 0;
}
else if (choice == 2){
cout << "Enter Celsius degrees to be converted: ";
cin >> cel;
fahr = 9.0 / 5.0 * cel + 32.0;
cout << cel << " degrees Celcius is " << fahr << " degrees Fahrenheit" << endl;
cout << "Please type a character followed by Enter, to end the program";
int stop; cin >> stop;
return 0;
}
else {
cout << "Not a valid option" << endl
<< "Please run program again...";
int stop; cin >> stop;
return 0;
}
}
}
return 0;
我必须输入我的选择两次,程序的其余部分才能运行。
在上面的例子中,我必须把我想要转换的温度,两次转换一次。我第一次把它放进去的时候,它只是换了一条新的线
有什么线索说明原因吗
编辑以包含代码和输出
if (cin >> choice) {
while (cin >> choice){
这要求输入两次
摆脱if
,只需在更改时执行
if (cin >> choice) {
while (cin >> choice){
到
您能否编辑您的问题以显示包含所有输出和输入的示例会话?任何可能更完整的程序(最好是a)?我猜这是因为if(cin>>choice){while(cin>>choice){
。你是对的!另外谢谢你,你可以删除while
,因为你在执行一个循环后返回(如果没有其他意图)谢谢!我不知道为什么我会把它放在那里。我甚至都没注意到。谢谢
if (cin >> choice) {
while (cin >> choice){
while (cin >> choice){ // you already got the input, don't need to read it twice.