0

Shy to ask but I cannot figure out why I get only the first character from guests->name in output ? How to print the whole string ?

#include <iostream>
using namespace std;

struct name_table {
    char name[20];
};

int main(){
    name_table *guests = new name_table;
    cout << "Please enter the the line:";
    cin.get(guests->name, 20);
    cout << "Okay, the line saved: " << *(guests)->name << endl;;

    cin.get();

    return 0;
}

Thank you

3 Answers 3

2
*(guests)->name
^^^^^^^^^^^^^^^
|^^^^^^^^^^^^^^
|      |
| guests->name
|      |
|  a char[20]
|      |
| becomes char*
| when passed into
|  operator<<
|
\
dereference

Applying dereference to the pointer gives you a single char.

tl;dr: You are printing a single character.

You can write:

guests->name

std::cin is already clever enough to treat the char* as a C-string and iteratively print the whole string, character by character.

However, I would advise reading into a std::string; in C++ you do not need to mess around with raw character arrays. Also, you have a memory leak and that dynamic allocation is totally needless.

Here's what I'd do:

#include <iostream>
#include <string>

int main()
{
   std::string name_table;
   std::cout << "Please enter the the line: ";
   std::getline(std::cin, name_table);
   std::cout << "Okay, the line saved: " << name_table << std::endl;
}
Sign up to request clarification or add additional context in comments.

Comments

1

guests is a pointer to your struct. In your output *(guests)->name, you use both the * and the -> operator, which get evaluated as follows:

  • (guests)->name first accesses the name member of the object behind the pointer guests. The parentheses are ignored / optional.

  • The so obtained char array is then dereferenced using the * operator, leading to a single char.

So what you really want is one of the following:

  • Either remove the *, and the parentheses can be removed: guests->name, like you did in your cin.get-line.

  • Or put the * in the parentheses to dereference guests and then use the . operator (instead of -> for accessing the member: (*guests).name

1 Comment

He doesn't really want either of those.
0

you have to remove * in your count line.

cout << "Okay, the line saved: " << (guests)->name << endl;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.