使用for循环时,C ++中的getline()错误

时间:2013-09-30 05:13:19

标签: c++ for-loop getline

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

在GNU编译器中使用C ++和Codeblocks IDE(我也尝试过其他编译器)

无论如何这里是代码。

#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;

}

1 个答案:

答案 0 :(得分:0)

当您读取循环运行的次数时,输入操作符会读取该数字,但会将新行留在缓冲区中。这意味着第一次调用getline会读取单个换行符,而不再是。{/ p>

为确保您在该号码之后跳过任何内容,包括换行符,您可以使用例如。

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');