Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

cin vs cin.get()

User image

Published by

sanya sanya

Published at: 27th Jul, 2023
2.035 mins read

cin:

Syntax:

cin >> variable;

Code:

#include

using namespace std;

int main() {

int num;

cout << "Enter a number: ";

cin >> num;

cout << "You entered: " << num << endl;

return 0;

}

Differences:

- cin is used to read input from the user in C++.

- It extracts formatted input from the standard input stream (usually the keyboard) and stores it in the specified variable.

- It skips leading whitespace and stops reading at the first whitespace encountered.

cin.get():

Syntax:

cin.get(character_array, size);

Code:

#include using namespace std;

int main() {

const int SIZE = 100;

char input[SIZE];

cout << "Enter a string: ";

cin.get(input, SIZE);

cout << "You entered: " << input << endl;

return 0;

}

Differences:

- cin.get() is used to read input including whitespace and newline characters.

- It reads input until the specified size is reached or a newline character is encountered (newline character is extracted but not stored in the character array).

- It allows reading input with spaces and can be used to read complete lines of text.

Applications:

- cin: It is commonly used to read individual values of different data types from the user, such as numbers or single words.

- cin.get(): It is useful for reading input containing spaces or when reading a complete line of text.

Advantages of cin:

- It provides a convenient and straightforward way to read formatted input.

- It is widely supported and understood by C++ programmers.

- It allows easy extraction of different data types.

Advantages of cin.get():

- It allows reading input with spaces and preserves whitespace.

- It can be used to read complete lines of text, which is useful for processing sentences or paragraphs.

- It provides more control over input reading compared to cin.

Disadvantages of cin:

- It stops reading input at the first whitespace encountered, which can lead to incorrect results when reading multiple words or phrases.

- If the input type does not match the variable type, it can result in input failures and leave the stream in an invalid state.

Disadvantages of cin.get():

- It requires specifying the size of the character array, which can lead to buffer overflow if the input exceeds the specified size.

- It is less commonly used compared to cin, so its usage might be less familiar to some programmers.

Library

WEB DEVELOPMENT

FAANG QUESTIONS