-2

i want the equivalent of this C# piece of code in C++

String name;
name=Console.ReadLine();

i tried the following code, but its not working!

struct node{string player_name};
    p=new struct node;
    getline(cin,p->player_name);
user3927214
  • 67
  • 2
  • 3
  • 9

2 Answers2

3
#include <iostream>
#include <string>
using namespace std;

int main(){
    string s;
    getline(cin,s);
    cout << s;
}

Try it here at http://ideone.com/AgLUGv

druckermanly
  • 2,694
  • 15
  • 27
  • Explaining a bit further: this is the best way in C++ to achieve the same intent as the Java code, lacking any further context. The Java version uses a different memory management strategy which we could emulate in C++ if we wanted to; however we don't want to because C++ has more memory management options available and this code shows the best one for the job. – M.M Aug 10 '14 at 21:54
1

The code you posted doesn't compile. It is missing a ; after player_name, for example. Here is a version that does compile:

#include <iostream>
#include <string>

struct node{
    std::string player_name;
};

int main()
{
   node * p= new node();
   std::getline(std::cin, p->player_name);
   delete p;
   return 0;
}

Of course there is a simpler way of doing this, you do not need to use new/delete you can create the object on the stack. The contents of player_name are created in the heap:

#include <iostream>
#include <string>

struct node {
    std::string player_name;
};

int main()
{
    node p;
    std::getline( std::cin, p.player_name);

    return 0;
}

If you want the equivalent of your C# code, then we can remove the node struct:

#include <iostream>
#include <string>

int main()
{
    std::string name;
    std::getline( std::cin, name);

    return 0;
}
tillaert
  • 1,797
  • 12
  • 20
  • 1
    You're forgetting `#include `. Your code may compile, because many compilers will automatically include the `string` library when you `#include ` but that's not necessarily the case. – druckermanly Aug 10 '14 at 21:47
  • Just because it compiles doesn't mean it's right. For instance, why are you allocating dynamically? – David G Aug 10 '14 at 22:23
  • @0x499602D2 Being "right" is a matter of opinion. The reason why I allocate dynamically is because the asker was allocating it dynamically. of course it is better use a `std::string` object, but by doing two things at the same time, the asker doesn't have the chance to learn something. – tillaert Aug 11 '14 at 05:22