-
please answer my query
please check the following code. arr should the 5 character array that we enter but in output it is appended by some extra characters may be they are garbage. Please tell me why it is happening and how to modify the code?
Code:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char arr[5];
for(int i=0;i<5;i++)
{
arr[i]=getch();
cout<<"*";
}
cout<<endl<<arr;
getch();
}
-
i think getch(), use (cin.get() c++ code) returns when it sees '\n' on next loop..
after getch()..add cin.get() or getch() again and that should consume the extra crap..
-
The garbage is because your string is not null terminated. C and C++ store strings in char arrays with a 0 at the end to tell the output call (cout, printf() etc.) where to stop.
In your case, the simple way to fix the problem is to make your array 1 bigger than your string and initialize it to all 0s...
-
The solution is to write portable, standard C++ code:
Code:
#include <iostream>
int main()
{
std::string string;
std::getline(string, std::cin);
std::cout << "*****\n" << string;
}
Get rid of iostream.h: it's non-standard.
Get rid of conion.h and getch: they're non-portable.
Use C++ facilities instead of C facilities.
Use int main instead of void main! void main is not standard!
-
dang! of course null terminated..reminds me why I'm kinda glad I am not studying C :O