What is the output of this C++ program? #include <iostream> using namespace std; int main () { char first, second; cout << "Enter a word: "; first = cin.get(); cin.sync(); second = cin.get(); cout << first << endl; cout << second << endl; return 0; } None of the mentioned First 2 characters of the sentence user enters second first
Question
What is the output of this C++ program?
#include <iostream>
using namespace std;
int main ()
{
char first, second;
cout << "Enter a word: ";
first = cin.get();
cin.sync();
second = cin.get();
cout << first << endl;
cout << second << endl;
return 0;
}
None of the mentioned
First 2 characters of the sentence user enters
second
first
Solution
The output of this C++ program will be the first two characters of the word the user enters.
Here's how it works:
-
The program starts by declaring two char variables,
firstandsecond. -
It then prompts the user to enter a word with the statement
cout << "Enter a word: ";. -
The
cin.get()function is used to get the first character the user enters and assigns it to thefirstvariable. -
The
cin.sync()function is used to clear the input buffer. This is necessary because when the user enters a word, the newline character (\n) that is entered when the user presses the Enter key is also stored in the buffer. Ifcin.sync()is not used, this newline character would be assigned to thesecondvariable. -
The
cin.get()function is used again to get the next character the user enters and assigns it to thesecondvariable. -
The program then prints the
firstandsecondcharacters on separate lines with thecout << first << endl;andcout << second << endl;statements. -
The program ends by returning 0, indicating that it has executed successfully.
So, the correct answer is "First 2 characters of the sentence user enters".
Similar Questions
What will be the output of the following C code?
What will be the output of the following program?
What will be the output of the C program? ans.09119011 Previous Marked for Review Next
What would be the output of the following program?#include <stdio.h>int main( ){int j=1;while (j <= 255){printf ( "%c %d\n ", j, j );j++;}return 0;}ans.
What will be the output of the following program?Note: This question helps in clearing AMCAT exam.12345678910#include <stdio.h>int main() { int c = 0, e = 0; for (e = 0;e < 5; e++) { c++; if (e == 3) break; } printf("%d",c);}
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.