Here is a listing of C++ interview questions on “File Streams and String Streams” along with answers, explanations and/or solutions:
1. Which operator is used to insert the data into file?
a) >>
b) <<
c) <
d) >
Answer: b
Clarification: You can write information to a file from your program using the stream insertion operator <<.
2. Which function is used to position back from the end of file object?
a) seekg
b) seekp
c) both seekg & seekp
d) seekf
Answer: a
Clarification: The member function seekg is used to position back from the end of file object.
3. How many objects are used for input and output to a string?
a) 1
b) 2
c) 3
d) 4
Answer: c
Clarification: The stringstream, ostringstream, and istringstream objects are used for input and output to a string.
4. What will be the output of the following C++ code?
-
#include -
#include -
using namespace std;
-
int main ()
-
{ -
int length;
-
char * buffer;
-
ifstream is; -
is.open ("sample.txt", ios :: binary );
-
is.seekg (0, ios :: end);
-
length = is.tellg();
-
is.seekg (0, ios :: beg);
-
buffer = new char [length];
-
is.read (buffer, length);
-
is.close();
-
cout.write (buffer, length);
-
delete[] buffer;
-
return 0;
-
}
a) This is sample
b) sample
c) Error
d) Runtime error
Answer: d
Clarification: In this program, if the file exist, it will read the file. Otherwise it will throw an exception. A runtime error will occur because the value of the length variable will be “-1” if file doesn’t exist and in line 13 we are trying to allocate an array of size “-1”.
5. What will be the output of the following C++ code?
-
#include -
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;
-
}
a) first
b) second
c) returns first 2 letter or number from the entered word
d) third
Answer: c
Clarification: In this program, We are using the sync function to return the first two letters of the entered word.
Output:
$ g++ stream.cpp $ a.out Enter a word: steve s t
6. What will be the output of the following C++ code?
-
#include -
#include -
using namespace std;
-
int main ()
-
{ -
ofstream outfile ("test.txt");
-
for (int n = 0; n < 100; n++)
-
{ -
outfile << n;
-
outfile.flush();
-
} -
cout << "Done";
-
outfile.close();
-
return 0;
-
}
a) Done
b) Error
c) Runtime error
d) DoneDoneDone
Answer: a
Clarification: In this program, We are using the flush function to update the contents in a file.
Output:
$ g++ stream1.cpp $ a.out Done
