user3002211
user3002211

Reputation: 183

Getline doesn't work as expected

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

I'm doing an exercise in c++ and it's supposed to take a car and its price, then return the prices in order from lowest to highest. The challenge is to use the algorithm given by the professor, so please don't mind that part (I think it's bad algorithm). I need to know why can't I use getline(cin, carname[i]); and cin >> carname[i]; works fine. I also tried using cin.clear(); and cin.ignore(); before the getline, still doesn't work. Any help is appreciated.

Upvotes: 1

Views: 281

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154025

Formatted input, i.e., using operator>>(), will skip leading whitespace. In addition, it will stop when a character is received which doesn't fit the format. For example, when reading a float, the input will read a number and stop upon the first whitespace received. For example, it will stop right before a newline used to enter the current value.

Unformatted input, e.g., using std::getline(), won't skip leading whitespace. Instead, it will happily read whatever character is waiting to be read. For example, if the next character is a newline, std::getline() will happily stop reading right there!

Generally, when switching from formatted to unformatted input, you want to get rid of some of the whitespace. For example, you can skip all leading whitespace with the std::ws manipulator:

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

Your inputs go entirely unchecked: not checking the result before using it is generally a bad idea! You should probably test the stream state at some point and possible restore it to good state, asking for correctly formatted data.

Upvotes: 2

Related Questions