Getline无法按预期工作

时间:2013-12-02 00:13:41

标签: c++ getline

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    int order[5];
    string carorder[5];
    int smallest=999999, where;
    string carname[5];
    float carprice[5];
    cout << "Enter car names then prices: ";
        cout << endl;
    for(int i=0; i < 5; i++){
        cin >> carname[i];
        //getline(cin, carname[i]);     can't do this -- why?
        cout << endl;
        cin >> carprice[i];
        cout << endl;
    }
    //BAD ALGORITHM//
       for(int m=0; m<5; m++){
    for(int j=0; j < 5; j++){

        if(carprice[j] < smallest){
            smallest = carprice[j];
            where = j;
        }

    }
    order[m] = smallest;
    carorder[m] = carname[where];
    carprice[where] = 999999;
    smallest = 999999;

   }
   //////////////////////////
    for(int w=0;  w<5; w++){
        cout << endl << "The car: " << carname[w] << " and price: " << order[w];
    }
    //////////////////////////
    return 0;
}

我正在用c ++进行练习,它应该采用汽车及其价格,然后按照从最低到最高的顺序返回价格。挑战是使用教授给出的算法,所以请不要介意那部分(我认为这是不好的算法)。我需要知道为什么我不能使用getline(cin,carname [i]);和cin&gt;&gt; carname [I];工作良好。我也尝试过使用cin.clear();和cin.ignore();在getline之前,仍然无法正常工作。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

格式化输入,即使用operator>>(),将跳过前导空格。此外,当收到不符合格式的字符时,它将停止。例如,当读取float时,输入将读取一个数字并在收到第一个空格时停止。例如,它将在用于输入当前值的换行符之前停止。

无格式输入(例如,使用std::getline())不会跳过前导空格。相反,它会愉快地读取等待阅读的任何字符。例如,如果下一个字符是换行符,则std::getline()将很快停止在那里阅读!

通常,当从格式化切换到无格式输入时,您想要摆脱一些空白。例如,您可以使用std::ws操纵器跳过所有前导空格:

std::getline(std::cin >> std::ws, carname[i]);

您的输入完全未经检查:在使用之前不检查结果通常是个坏主意!您应该在某个时刻测试流状态,并可能将其恢复到良好状态,并要求格式正确的数据。