cin.get(ch) and ch = cin.get()

Hi! I'm kinda confused when to use 1. cin.get(ch) and 2. ch = cin.get().

Here's a code. Not sure if it is useful or not.

This is an exercise from C++ Primer Plus, while the code is from another user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  int getinfo(student pa[], int n){
  cout << "Enter Information of Students:\n";
  //cin.get();
  int i;
  char name [SLEN];
  for (i=0; i < n; i++) {
    cout << "Student Name: ";
    char ch;
    ch = cin.get();
    if (ch == '\n'){
      break;
    }
    cin.getline(name, SLEN-1);
    pa[i].fullname[0] = ch;
    strcat(pa[i].fullname, name);
    
    cout << "Hobby: ";
    cin.getline(pa[i].hobby, SLEN);
    
    cout << "OOP Level: ";
    cin >> pa[i].ooplevel;
    cin.get();

  }
  return i;
}
closed account (SECMoG1T)
you can use them interchangeably
Note that cin.get() returns an integer, so if you use it as a if/loop condition you have to make sure to store the result as an int to be able to check if it returned a end of file value.
1
2
3
4
5
int ch;
while ((ch = cin.get()) != std::ios::eof())
{
	// ...
}

cin.get(ch) works more similar to other read functions like >> and getline in that it returns a reference to the cin stream so that you can use it in a if/loop just as it is. I personally think this is often more convenient.
1
2
3
4
5
char ch;
while (cin.get(ch))
{
	// ...
}
Last edited on
Oh okay, thank you!
Topic archived. No new replies allowed.