簡體   English   中英

使用getline的垃圾值

[英]Garbage value with getline

#include<iostream.h>
#include<conio.h>

void main()
{
    clrscr();
    char c[50];

    //cin>>c;
    cin.getline(c,50);

    //cout.write(c,50);
    cout<<c;
    getch();
}

如果輸入少於50個字符,則會得到垃圾值。 為什么會這樣呢?

您沒有初始化數組:

#include<iostream>
#include<conio.h>
using std::cout;
using std::cin;

int main()
{
    clrscr();

    char c[50] = {};//initialize your array here!

    cin.getline(c,50);
    cout<<c;

    getch();

    return 0;
}

也:

  • iostream.h已過時。
  • 如果您打算跨平台開發,請避免: <conio.h> ,因此, 它定義函數在您的代碼中使用: clscr()getch()
  • 如果可以,請避免使用C字符串。 您正在使用C ++,請使用: <string>庫和std::string 在此處閱讀有關此內容的更多信息: C字符串與C ++字符串的效率
  • 可以使用cin.getline()為緩沖輸入提供類似的參數,但是我不知道您的最終目標,因此我無法對此發表足夠的評論。 但是,似乎您正在嘗試進行緩沖輸入。

簡單干凈的方法

#include<iostream>
#include<string>
int main()
{
    std::string str;
    getline(std::cin, str);
    cout<<str;
    std::cin.get();    //or std::cin.ignore();
}

需要注意的幾點:

  1. 新標准規定main()的返回類型應為int而不是void (不返回任何默認值返回int return)

  2. 甚至getchar()也已過時。

  3. 使用std::string insteead char數組,因為它易於實現且安全

使用指定的答案時,我也遇到同樣的問題,因為我沒有意識到我的文件是用16位編碼的。 所以我不得不使用std :: wstring(和std :: wifstream)。

暫無
暫無

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

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