简体   繁体   English

为什么getline如此不一致?

[英]Why is getline so inconsistent?

I am at the computer lab and none of the tutors can figure out why my getline is not working correctly. 我在计算机实验室,没有一个导师可以弄清楚为什么我的getline工作不正常。 It is not storing the information correctly (only stores 1 or 2 letters). 它没有正确存储信息(只存储1或2个字母)。 Does anyone know why this is so? 有谁知道为什么会这样?

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

std::istream::ignore (ie cin.ignore() )'s first argument is the number of characters to discard. std::istream::ignore (即cin.ignore() )的第一个参数是要丢弃的字符数。 The value of '\\n' has an ASCII code of 10, so that '\\n' is being implicitly converted to an integer (most likely 10, but it could differ if a different encoding is used - EBCDIC uses 21), and that's how many characters are being ignored, leaving a few left over. '\\n'的值的ASCII码为10,因此'\\n'被隐式转换为整数(很可能是10,但如果使用不同的编码则可能会有所不同 - EBCDIC使用21),那就是被忽略了多少个字符,留下了一些字符。

What you actually want is to discard the maximum possible number until you find a newline: 您真正想要的是在找到换行符之前丢弃最大可能的数字:

#include <limits> //for numeric_limtis
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM