当循环时,在c++中的cin.get()之前循环两次

While Loop, Loops twice before cin.get() in c++

本文关键字:循环 两次 cin c++ 中的 get      更新时间:2023-10-16

每次我都试图使用cin.get()来暂停循环。

prodAtr.h:

#ifndef PRODATR
#define PRODATR
#include <array>
#include <vector>
#include <string>
extern std::array<std::string, 6> sProductType = { //Array contents here };
extern std::vector<std::vector<double>> nProductRates = {
    { //Array contents here },
    { //Array contents here },
    { //Array contents here },
    { //Array contents here },
    { //Array contents here },
    { //Array contents here }
};
#endif

Wholesale.cpp:

#include "stdafx.h"
#include <iostream>
#include "prodAtr.h"
int ShowProdOpt();
float GetCost();
void CalulateTiers(float, int);

int main()
{
    using namespace std;
    float fCost = GetCost();
    cout << endl;
    int nOptChoice = ShowProdOpt();
    CalulateTiers(fCost, nOptChoice);
    return 0;
}
int ShowProdOpt()
{
    using namespace std;
    cout << "Please select you product type: " << endl;
    for (unsigned int i = 0; i < sProductType.size(); i++)
    {
        cout << "[" << i + 1 << "]" << sProductType[i] << " ";
    }
    cout << endl;
    int nResult;
    cin >> nResult;
    return nResult;
}
float GetCost()
{
    float fCost;
    std::cout << "What is the cost? $";
    std::cin >> fCost;
    return fCost;
}
void CalulateTiers(float fCost, int nType)
{
    using namespace std;
    int iii = 0;
    while(iii < 10)
    {
        int jjj = iii + 1;
        float fPrice = floor(((nProductRates[nType - 1][iii] * fCost) + fCost) * 100 + 0.5) / 100;
        cout << "Tier[" << jjj << "]: $" << fPrice << endl;
        cin.get();
        iii++;
    }
}

VS 2013日志输出(减去文件位置信息):

========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

但我的结果是:

Tier[1]: $1.34
Tier[2]: $1.22

然后cin.get()似乎会暂停并从那里正常工作。

如何在每次执行循环后让cin.get()暂停?

我不能给出一个明确的答案,因为你还没有提供更多的代码,但你的cin缓冲区中似乎已经有了一些东西,所以它在get()中接受了这些并继续执行。

在进入循环之前,请尝试刷新缓冲区。

SEE:如何冲洗cin缓冲液?

好的,我添加了

cin.clear();
cin.ignore();

就在while循环之前。现在它按要求工作。