簡體   English   中英

結合使用cin.getline和fgets時防止緩沖區溢出

[英]Prevent buffer overflow when using cin.getline and fgets in conjugation

問題是字符串的大小很小。 因此,溢出位將分配給下一個字符串。

我最近才知道,在使用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;
}

在此處輸入圖片說明

您可以使用老式的c方法使用getchar跳過其余部分。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM