【问题标题】:Prevent buffer overflow when using cin.getline and fgets in conjugation在共轭中使用 cin.getline 和 fgets 时防止缓冲区溢出
【发布时间】:2016-04-23 15:29:27
【问题描述】:

问题是字符串的大小很小。所以溢出的位被分配给下一个字符串。

我最近知道,在使用 getline 时,我们不应该使用 fflush(stdin) 来丢弃输入流中不需要的序列,因为它具有未定义的行为。人们建议改用 cin.ignore()

但是我们应该使用什么来使用 fgets 忽略输入流中不需要的序列?

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;

int main() {
    string cpp;
    char c1[6];
    char c2[5];

    // Reading C++ string: GETLINE
    getline( cin, cpp);

    // Reading C string: CIN.GETLINE
    cin.getline( c1, sizeof(c1) );

    // cin.ignore(); DOESNT WORK
    // fflush(stdin); UNDEFINED BEHAVIOR


    // Reading C string: FGETS
    fgets( c2, sizeof(c2), stdin);

    cout << " " << cpp << '\n' << c1 << '\n' << c2 << '\n';

    return 0;
}

【问题讨论】:

  • 您能否给出一个示例输入、观察到的输出和期望的输出。
  • @user2079303 完成。实际上所需的输出是能够输入字符串c2。目前,溢出的字符被存储到 c2 中。

标签: c++ string stdin buffer-overflow istream


【解决方案1】:

您可以使用老式的c way 跳过使用getchar 的其余行。

char c;
while((c = std::getchar()) != '\n' && c != EOF);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多