Getline 无法按预期工作
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;
}
我正在用 c++ 做一个练习,它应该拿一辆车和它的价格,然后按从低到高的顺序返回价格。挑战在于使用教授给出的算法,所以请不要介意那部分(我认为这是糟糕的算法(。我需要知道为什么我不能使用 getline(cin, carname[i](;和 CIN>> carname[i];工作正常。我也尝试使用cin.clear((;和 cin.ignore((;在获取线之前,仍然不起作用。任何帮助,不胜感激。
格式化输入,即使用 operator>>()
,将跳过前导空格。此外,当收到不符合格式的字符时,它将停止。例如,当读取一个float
时,输入将读取一个数字并在收到的第一个空格时停止。例如,它将在用于输入当前值的换行符之前停止。
未格式化的输入,例如,使用 std::getline()
,不会跳过前导空格。相反,它会愉快地阅读任何等待阅读的字符。例如,如果下一个字符是换行符,std::getline()
会很高兴地停止阅读!
通常,从格式化输入切换到无格式输入时,您希望删除一些空格。例如,您可以使用std::ws
操纵器跳过所有前导空格:
std::getline(std::cin >> std::ws, carname[i]);
您的输入完全不受检查:在使用之前不检查结果通常是一个坏主意!您可能应该在某个时候测试流状态,并可能将其还原到良好状态,要求提供格式正确的数据。
相关文章:
- getline() 上的分隔符无法正常工作
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- 如何在使用getline后使cin工作
- 如何使 getline 命令在 while 循环中工作
- 对Getline的工作方式有更深入的深度
- C getline()函数无法按预期工作
- C STD :: getline / std :: Sort无法正常工作
- C++ while(getline()) 无法正常工作
- CIN.IGNORE如何与CIN和Getline一起工作
- cin.getline()函数在CIN之后无法正常工作
- C - getline stdin eof无法正常工作
- Getline 无法按预期使用字符串工作
- cin.getline()未按预期工作
- C++ cin.getline() 不能在循环中工作
- cout在获取行输入(getline)后无法在c++中工作
- Getline 无法按预期工作
- 通过getline()输入,正则表达式无法正常工作
- 我怎样才能让getline操作符工作
- Cin.getline 无法正确打印也无法正常工作
- std::getline() 访问冲突,以前可以工作,但现在无法从任何文件中读取