-4

I new to programming and was trying to implement struct program in c++, it's simple program but it's not printing proper result. please tell me why?

#include <iostream>
using namespace std;
struct classroom {
    int number;
    char name[9];
    int marks;
    void getAndPrint()
    {
        cout << "struct classroom ";
        cin >> number;
        cout << number << '\n';

        cin.get(name, 9);
        //cin>>name;
        cout << name;

        cin >> marks;
        cout << marks;
    }
};
int main()
{
    classroom room1;
    room1.getAndPrint();
    int i;
    cin >> i;
    return 0;
}

In function getAndPrint() I'm using cin.get()..the compiler execute the properly till printing the "number" but when it comes on cin.get(name,9) it print garbage and skips the rest of the code inside the funcion. If i use cin>>name then it's working properly. Can anyone tell what exactly is the problem?

berry
  • 29
  • 3
  • You might want to read about `cin.get`, don't think its doing what you expect. C++ streams are important to understand. Also, on an unrelated note, you never call your function. – Ashwin Gupta Dec 14 '16 at 03:09
  • 1
    You need to read the chapter in your C++ book that talks about C++ streams, with specific emphasis on formatted and unformatted operations. – Sam Varshavchik Dec 14 '16 at 03:10
  • 1
    Don't use `char[]` unless you *really* need to - `std::string` is easier! – Jack Deeth Dec 14 '16 at 03:11
  • @JackDeeth well, not sure if thats exactly good advice all the time. Their are thousands of old libraries and things that used char[] as parameters for their functions where std::string could work. The OP should be comfortable with using `char[]` like that or as a pointer. – Ashwin Gupta Dec 14 '16 at 03:12

2 Answers2

2

first, in C++, struct is class with access_modifier is public. second, you should try read: Difference between cin and cin.get() for char array

Community
  • 1
  • 1
xcodedeveloper
  • 266
  • 2
  • 8
0

The structure definition does not contain such a function like see

room1.see();
      ^^^^

I think you mean

room1.getAndPrint();

Also before this statement

cin.get(name, 9);

insert at least this statement

cin.ignore();

Or you even can include the header <limits> and insert statement

#include <limits>

//...

cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335