0
#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();
}

I get garbage value if i input anything less than 50 characters. Why is it so ?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204

3 Answers3

1

You didn't initialize your array:

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

Also:

  • iostream.h is outdated.
  • If you're aiming for cross-platform development avoid: <conio.h> and consequently, the functions it defines used in your code: clscr() and getch().
  • Avoid C-Strings where possible, if you can. You're using C++, use: the <string> library and std::string. Read more about that here: Efficiency of C-String vs C++Strings
  • A similar argument can be made for buffered input, using cin.getline(), but I don't know your ultimate goal, so I can't comment adequately on that. But, it does seem like you're trying to do a buffered input.
Community
  • 1
  • 1
jrd1
  • 10,358
  • 4
  • 34
  • 51
0

A simple and clean approach

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

Some points to be noted:

  1. The new standard specifies that main() should have a return type of int and not void.(not returning anything defaults to int return)

  2. Even getchar() is obsolete.

  3. use std::string insteead char arrays as it is easy and safe to implement

Saksham
  • 9,037
  • 7
  • 45
  • 73
0

I also had the same problem using the specified answers, because I didn't realize my file was encoded in 16 bits. So I had to use std::wstring (and std::wifstream).

MGamsby
  • 386
  • 4
  • 13