我在计算机实验室,没有一个老师能弄清楚为什么我的getline不能正常工作。它没有正确存储信息(仅存储1或2个字母)。有人知道为什么会这样吗?
void addMovie(Inventory movie[], int &count)
{
string s;
int i;
cout << "Please enter the SKU " << endl;
cin >> i;
movie[count].sku = i;
cout << "Please enter the name of the movie you wish to add " << endl;
cin.ignore('\n');
getline(cin, s, '\n');
movie[count].title = s;
count++;
}发布于 2012-09-19 08:36:13
std::istream::ignore (即cin.ignore())的第一个参数是要丢弃的字符数。'\n'的值具有ASCII码10,因此'\n'将被隐式转换为整数(最有可能是10,但如果使用不同的编码,它可能会有所不同- EBCDIC使用21),这就是忽略的字符数,留下一些剩余的字符。
你真正想要的是丢弃最大可能的数字,直到你找到一个换行符:
#include <limits> //for numeric_limtis
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');https://stackoverflow.com/questions/12486900
复制相似问题