【发布时间】:2013-12-02 00:13:41
【问题描述】:
#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 >> carname[i];工作正常。我也尝试使用 cin.clear();和 cin.ignore();在getline之前,仍然不起作用。任何帮助表示赞赏。
【问题讨论】: