2014-10-02 63 views
-3

我想实现输入验证到这个程序,但它一直出错。我尝试使用另一个声明,但它没有奏效。它通常弹出与不应该的文本。我希望它在人们输入错误信息后显示。我希望如此,如果输入的数据无效,他们将不得不重新输入。如何将输入验证合并到此代码中?

这是我到目前为止的代码。

/* 
1. Declare variables for month 1, 2, and 3. 
2. Declare variable for Total and Average Rainfall 
3. Ask user to input name of months. 
4. Then ask user to input inches of rain fall. 
5. Add all inches and then divide by number of inches asked. In this case, 3. 
6. Display average inches of rain for all months to user. 
*/ 

#include <iostream> 
#include <iomanip> 
#include <string> 

using namespace std; 

int main() 

{ 
string month1, month2, month3;//Declared values for months aswell as total and average rainfall. 
double month1Inch, month2Inch, month3Inch; 
double averageInches; 
double totalInches; 
char c = 'y'; 

do 
{ 

    cout << setprecision(2) << fixed; 
    cout << "Enter first month's name:"; 
    cin >> month1; 
    cout << "Enter rain inches for " << month1 << ":"; 
    cin >> month1Inch; 

    cout << "\n"; 

    cout << "Enter second month's name:"; 
    cin >> month2; 
    cout << "Enter rain inches for " << month2 << ":"; 
    cin >> month2Inch; 

    cout << "\n"; 

    cout << "Enter third month's name:"; 
    cin >> month3; 
    cout << "Enter rain inches for " << month3 << ":"; 
    cin >> month3Inch; 

    cout << "\n"; 

    totalInches = (month1Inch + month2Inch + month3Inch); 
    averageInches = (totalInches)/3;//calculating the average 

    //Display calculated data. 
    cout << "The average rainfall for " << month1 << ", " << month2 << ", " << "and " << month3 << " is " << averageInches << endl; 

    cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl; 
    cin >> c; 


} while (c == 'Y'||c=='y'); 

if (c != 'Y' || c != 'y') 
    cout << "you must enter the correct choice" << endl; 

system("pause"); 
return 0; 

} 

我试图把一个如果在“COUT < <”你想声明重新计算?输入Y运行或N不运行。“< < endl; cin >> c;”但我得到一个无限循环。

我没有收到任何错误代码。只是显示“你想重新计算?”的文字吗?线和无限循环。

即使我输入的数据显示,我得到一个无限循环的地方。所以我删除了它。

+1

所以,你最终向我们展示的代码甚至没有试图做你想要的,并要求我们为你写。 SO不是代码写入服务。 – 2014-10-02 20:52:59

+0

帮你一个忙,摆脱'main()'中的所有冗余注释。 – blackbird 2014-10-02 21:00:05

+0

@Anton Savin,我再次添加了我之前的代码。 – user2221218 2014-10-02 21:03:24

回答

1

听起来你想验证是或否回应。这需要一个只有当您有可接受的输入时才退出的循环。它与循环分开,决定是否应该再次运行计算。

int main() { 
    // ... 
    do { 
    // ... 

    do { 
     cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl; 
     cin >> c; 
    } while (c != 'Y' && c != 'y' && c != 'N' && c != 'n'); 
    } while (c == 'Y'|| c=='y'); 

    system("pause"); 
    return 0; 
}