c++ - getline 的垃圾值

标签 c++ getline garbage

#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>因此,functions it defines在您的代码中使用:clscr()getch() .
  • 尽可能避免使用 C 字符串。你正在使用 C++,使用:<string>图书馆和std::string .在这里阅读更多相关信息:Efficiency of C-String vs C++Strings
  • 可以对缓冲输入进行类似的论证,使用cin.getline() ,但我不知道你的最终目标,所以我不能对此发表充分的评论。但是,您似乎确实在尝试进行缓冲输入。

关于c++ - getline 的垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171352/

相关文章:

c++ - 如何处理堆内存垃圾?

c++ - 如何正确多次使用stringstream类

c++ - getline() valgrind 内存泄漏

c++ - 使用 boost odeint 的 DDE

c++ - 在 cin 之后使用 getline(cin, s)

c++ - C++ 中的 getline(isstream, string)

java - 由从未引用的对象创建的垃圾

c++ - C++程序奇怪输出的原因

c++ - CodeBlocks 不能插入括号

c++ - 值传递会影响递归算法的渐近时间复杂度吗?