0

我必须编写一个程序来计算汽车在旅途中的平均速度,并且我必须提示用户输入他们正在旅行的两个城市的名称。该程序有效,但我们必须编写的下一个程序是对上一个程序的补充,其中提示用户程序应该运行多少次。我为用户需要程序运行的次数声明了一个新变量。然而,当程序进入循环时,它会跳过第一个 getline() 方法(询问始发城市)并直接跳到第二个 getline()(询问目的地城市的方法)。我尝试清除缓冲区并以不同的方式声明循环,但无论我做什么,字符串仍然作为空字符串读入程序。只是想知道我是否在某些事情上犯了错误,或者在这种情况下我是否无法使用 getline() 。

将 C++ 和 Codeblocks IDE 与 GNU 编译器一起使用(我也尝试过其他编译器)

无论如何,这里是代码。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    //Declare Variables
    string orgcity = "";
    string destcity = "";
    int hours = 0;
    double minutes = 0.0;
    int hoursmin = 0;
    int minutesmin = 0;
    int minutesmax = 60;
    double dist = 0.0;
    double totalhours = 0.0;
    double avespeed = 0.0;
    double num1 = 0;

    cout << "How many times would you like to calculate the average speed: ";
    cin >> num1;

    for(num1; num1 > 0; --num1)
    {

    //Collect Data
    cout << "Enter the city of origin: ";
    getline(cin, orgcity);

    cout << "Enter the destination city: ";
    getline(cin, destcity);

    //If Statements and Loops...Start here
    do {
        cout << "Enter the number of hours spent in travel: ";
        cin >> hours;

        if (hours < hoursmin)
            cout << "     Invalid number of hours - must be >= 0" << endl;

    } while (hours < hoursmin);

    do {
    cout << "Enter the number of minutes spent in travel: ";
    cin >> minutes;

    if (minutes >= minutesmax){
    cout <<"     Invalid number of minutes - must be in range 0..59" << endl;
    }
    if (minutes <= minutesmin) {
        cout << "     Invalid number of minutes - must be in range 0..59" << endl;
    }
    } while (minutes >= minutesmax);

    //End Here

    cout << "Enter the distance (in miles) between the two cities: ";
    cin >> dist;
    cout << endl;

    //Formula and Final Prompt
    totalhours = (hours + (minutes / 60.0));
    avespeed = dist / totalhours;

    cout << "The average speed of the vehicle traveling" << endl;
    cout << "between " << orgcity << " and " << destcity << " is " << fixed << setprecision(2) << avespeed << " miles per hour." << endl;
    cout << "-------------------------------------------------------------------------------" << endl;
    }
    return 0;

}
4

1 回答 1

0

当您读取循环应该运行的次数时,输入运算符会读取该数字,但将换行符留在缓冲区中。这意味着第一次调用getline读取该单个换行符,仅此而已。

为了确保您跳过该数字之后的任何内容,直到并包括换行符,您可以使用例如

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
于 2013-09-30T05:15:03.603 回答