C ++必须输入两次

时间:2014-01-29 04:01:55

标签: 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 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;

}

程序的输出是:

Please choose 1 for Fahrenheit, or 2 for Celsius conversion: 1
1
Enter Fahrenheit degrees to be converted: 32
32 degrees Fahrenheit is 0 degrees Celsius

我必须输入两次选择,以便程序的其余部分运行。 在上面的例子中,我必须将我想要转换的温度,两次转换为一次。我第一次把它放进去,它只是移动到新的一行。

任何关于为什么的线索?

已修改为包含代码和输出

2 个答案:

答案 0 :(得分:2)

if (cin >> choice) {
    while (cin >> choice){

这要求输入两次。

摆脱if,然后执行while

答案 1 :(得分:0)

更改

if (cin >> choice) {
    while (cin >> choice){

while (cin >> choice){ // you already got the input, don't need to read it twice.