c++ - Weird output at the end of string in Ubuntu terminal -


i trying c++ in ubuntu terminal. getting weird symbols @ end of strings.(this happened in past in codeblocks ubuntu worked fine in codeblocks windows).

here code:

#include <iostream> using namespace std;  int main() {     char name[20];     cout << "\nenter name: ";     cin.getline(name, 20);     cout << "\nhello ";     cout.write(name, 20);     return 0; } 

output:

enter name: yash  hello yash�@��fy 

i have checked other threads same problem. of them had assignment problems users did not add '\0' @ end. here doing no such thing. why these characters @ end?

cout.write(name, 20); 

will (try to) write 20 characters, not check '\0'. can check such things in favorite reference.

if want use char[] this, should write

cout << name; 

that check terminating character.

however, better ditch c-style strings , move std::string instead:

int main () {     std::string name;     std::cout << "\nenter name: ";     std::getline(std::cin, name);     std::cout << "\nhello ";     std::cout << name; } 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -