String and Stream Questions with Answers

20 practice questions on String and Stream (C++) with answers and step-by-step solutions. Try 10 samples below, then practise all 20 free in the AptiNest app.

Sample questions

Question 1Medium

What is the output of this program?

    #include<iostream>
    #include<fstream>
    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;
    }
  1. Done
  2. Error
  3. Runtime error
  4. None of the mentioned

Answer: A. Done

Explanation

In this program, We are using the flush function to update the contents in a file.

Step-by-step solution

  1. The loop writes the numbers 0 to 99 to test.txt, flushing after each write.
  2. The file writes do not print anything to the screen.
  3. After the loop, cout prints 'Done', which is option A.

Why the other options are wrong

  • B. No error is raised; the file opens and writes normally.
  • C. No run time error occurs in this program.
  • D. Option A is printed, so 'none' is wrong.

Tip: flush() pushes buffered data to the file now; it does not change what is printed to the screen.

Question 2Medium

100 oranges are bought at the rate of Rs. 350 and sold at the rate of 48 per dozen. The percentage of profit is

  1. 12.27%
  2. 13.27%
  3. 14.29%
  4. 15.27%

Answer: C. 14.29%

Explanation

So before solving this question we will get the C.P. and S.P. of 1 article to get the gain percent.

C.P. of 1 orange
= 350/100
= ₹3.50

S.P. of one orange
= 48/12
= ₹4 [note: divided by 12 as 1 dozen contains 12 items]

Gain
= 4 - 3.50
= ₹0.50

Gain%=0.50/3.50?100=100/7%=14.27%

Step-by-step solution

  1. Cost price of 100 oranges = ₹350.
  2. Selling price = 100 ÷ 12 × 48 = ₹400.
  3. Profit = 400 - 350 = 50.
  4. Profit % = 50 ÷ 350 × 100 = 14.29%, option C.

Why the other options are wrong

  • A. 12.27% is too low for a profit of 50 on 350.
  • B. 13.27% is too low for a profit of 50 on 350.
  • D. 15.27% is too high for a profit of 50 on 350.

Tip: Profit % = profit ÷ cost price × 100.

Question 3Medium

What is the output of this program?

    #include <iostream>
    #include <string>
    using namespace std;
    int main ()
    {
        string str ("Steve jobs founded the apple");
        string str2 ("apple");
        unsigned found = str.find(str2);
        if (found != string :: npos)
            cout << found << '\n';
        return 0;
    }
  1. apple
  2. 12
  3. 23
  4. Steve jobs founded the

Answer: C. 23

Explanation

In this program, We are finding a string by using the find method.

Output:
23

Step-by-step solution

  1. Find returns the position of the first match of apple in the string, counting from 0.
  2. The characters before apple are Steve (0 to 4), space (5), jobs (6 to 9), space (10), founded (11 to 17), space (18), the (19 to 21) and space (22).
  3. So apple starts at position 23, which is the value of found.
  4. So the output is 23.

Why the other options are wrong

  • A. Apple is the search text, not the position that is printed.
  • B. 12 is one place past the start of founded, not where apple starts.
  • D. Steve jobs founded the is the text before apple, not a position.

Tip: Count from 0 when reading the result of find, and count spaces carefully.

Question 4Medium

What is the output of this program?

    #include <iostream>
    #include <cstring>
    #include <string>
    using namespace std;
    int main ()
    {
        string str ("Steve jobs");
        char * cstr = new char [str.length() + 1];
        strcpy (cstr, str.c_str());
        char * p = strtok (cstr," ");
        while (p != 0)
        {
            cout << p << '\n';
            p = strtok(NULL," ");
        }
        delete[] cstr;
        return 0;
    }
  1. Steve jo
  2. Steve jobs
  3. Steve
  4. None of the mentioned

Answer: B. Steve jobs

Explanation

In this program, We are breaking up the strings into the form of tokens.

Output:
Steve jobs

Step-by-step solution

  1. Str holds Steve jobs, and strcpy copies it into cstr.
  2. Strtok splits cstr at each space, giving the tokens Steve and jobs.
  3. The while loop prints each token on its own line.
  4. The output is Steve on one line and jobs on the next, which is the text Steve jobs.

Why the other options are wrong

  • A. Strtok returns whole words, so Steve jo is not a token.
  • C. Steve is only the first token; jobs is printed too.
  • D. Option B matches the output, so none of the mentioned is wrong.

Tip: Strtok returns each word separately, and each one is printed on its own line.

Question 5Medium

What is the output of this program?

    #include <iostream>
    #include <ios>
    #include <istream>
    #include <limits>
    using namespace std;
    template < typename CharT>
    void ignore_line ( basic_istream<CharT>& in )
    {
        in.ignore ( numeric_limits<streamsize> :: max(), in.widen ( '\n' ) );
    }
    int main()
    {
        cout << "First input: ";
        cin.get();
        cout << "Clearing cin.\n";
        cin.clear();
        ignore_line ( cin );
        cout << "All done.\n";
    }
  1. First input
  2. Clearing cin
  3. Error
  4. None of the mentioned

Answer: D. None of the mentioned

Explanation

In this program, We are getting the input and clearing all the values.

Output:
First input: 4
Clearing cin.
All done.

Step-by-step solution

  1. cin.get() reads one character from input, and the program waits until a key is pressed.
  2. The output starts with First input: and then Clearing cin. is printed.
  3. cin.clear and ignore_line only reset the stream state and skip characters, and print nothing.
  4. All done. is printed, and no error occurs.
  5. The answer is None of the mentioned.

Why the other options are wrong

  • A. First input is only part of the output, and the program goes on to print more.
  • B. Clearing cin is only part of the output, and All done is also printed.
  • C. No error occurs, since the stream operations are valid.

Tip: Read the whole output before choosing; partial options are often incomplete.

Question 6Medium

What is the output of this program?

#include <stdio.h>
int main ()
{
    int n;
    FILE * p;
    char buffer [5];
    p = fopen ("myfile.txt", "w+");
    for ( n = 'A'; n <= 'D'; n++)
        fputc ( n, p);
    rewind (p);
    fread (buffer, 1, 5, p);
    fclose (p);
    buffer[3] = '\0';
    puts (buffer);
    return 0;
}
  1. ABCD
  2. ABC
  3. ABCDE
  4. None of the mentioned

Answer: B. ABC

Explanation

fputc writes ABCD to the file, and rewind and fread read it back. buffer[3] is set to the null character, which ends the string after ABC, so puts prints ABC.

ABC

Step-by-step solution

  1. The for loop writes A, B, C and D into the file, which is 4 bytes.
  2. Rewind moves back to the start, and fread reads the 4 bytes into buffer.
  3. buffer[3] is set to the null terminator, so the string is cut to the first 3 characters, ABC.
  4. So puts prints ABC.

Why the other options are wrong

  • A. buffer[3] is set to the null terminator, so the D is removed.
  • C. Only 4 bytes are written and read, and buffer[3] cuts the string at 3 characters.
  • D. ABC is a valid output, so none of the mentioned is wrong.

Tip: Check where the null terminator is placed before reading the printed string.

Question 7Medium

What must be specified when we construct an object of class ostream?

  1. stream
  2. streambuf
  3. memory
  4. None of the mentioned

Answer: B. streambuf

Explanation

If you construct an object of class ostream, you must specify a streambuf object to the constructor.

Step-by-step solution

  1. Constructing an ostream object needs a streambuf object passed to its constructor.
  2. A streambuf is the buffer that the stream writes its data through.
  3. A stream or memory object is not what the ostream constructor needs.
  4. So the answer is option B, streambuf.

Why the other options are wrong

  • A. A stream is the object being built, not the argument it needs.
  • C. Memory is not the argument that the ostream constructor needs.
  • D. Option B is required, so 'none of the mentioned' is wrong.

Tip: Stream classes work through a streambuf; the buffer is the argument to pass when building one.

Question 8Medium

What is the output of this program?

    #include <iostream>
    #include <string>
    using namespace std;
    int main ()
    {
        string str ("Steve jobs");
        unsigned found = str.find_first_of("aeiou");
        while (found != string :: npos)
        {
            str[found] = '*';
            found = str.find_first_of("aeiou", found + 1);
        }
        cout << str << '\n';
        return 0;
    }
  1. Steve
  2. jobs
  3. St*v* j*bs
  4. St*v*

Answer: C. St*v* j*bs

Explanation

In this program, We are replacing the vowels with a asterisk by using find_first_of method.

Output:
St*v* j*bs

Step-by-step solution

  1. Str is 'Steve jobs', and find_first_of finds vowels: e at index 2, e at index 4 and o at index 7.
  2. Each vowel found is replaced with '', giving 'St*v j*bs'.
  3. So the printed output is St*v* j*bs, which is option C.

Why the other options are wrong

  • A. The vowels are replaced, so the word Steve is not printed unchanged.
  • B. The word jobs is not the whole output; the first word is also changed.
  • D. St*v* is only part of the output, since the second word is changed too.

Tip: Find_first_of with a set of characters finds the next matching character; use a loop to replace each match.

Question 9Medium

What is the output of this program?

    #include <iostream>
    #include <locale>
    using namespace std;
    int main()
    {
        locale mylocale("");
        cout.imbue( mylocale );
        cout << (double) 3.14159 << endl;
        return 0;
    }
  1. 3.14
  2. 3.14159
  3. Error
  4. None of the mentioned

Answer: B. 3.14159

Explanation

In this program, We are using the locale and then assigning the type to the value.

Output:
3.14159

Step-by-step solution

  1. cout.imbue(mylocale) sets the locale used for output formatting.
  2. Cout << 3.14159 with no manipulators uses the default precision of 6 significant digits.
  3. 6 significant digits can show 3.14159 in full, so nothing is cut off.
  4. The output is 3.14159.

Why the other options are wrong

  • A. 3.14 needs a precision of 3; the default precision is 6.
  • C. Setting a locale does not cause an error here.
  • D. The program prints a value, so None of the mentioned is wrong.

Tip: Default cout precision is 6 significant digits.

Question 10Medium

What is the output of this program?

    #include <iostream>
    #include <fstream>
    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;
    }

(Assume sample.txt does not exist.)

  1. This is sample
  2. sample
  3. Error
  4. Runtime error

Answer: D. Runtime error

Explanation

The program never checks that sample.txt opened. When the file is missing, tellg() returns -1, so new char[-1] fails at run time (bad_array_new_length) and the program aborts.
So the expected result, without the file, is a runtime error.

Step-by-step solution

  1. The question gives no sample.txt, so assume the file is missing.
  2. is.open fails, so seekg fails and tellg returns -1.
  3. Length is -1, and new char[-1] throws std::bad_array_new_length.
  4. The exception is not caught, so the program stops with a runtime error before writing anything.
  5. The result is Runtime error.

Why the other options are wrong

  • A. This prints the file text only if sample.txt exists; here the program crashes first.
  • B. Nothing is written because the program crashes at the new statement.
  • C. The code compiles, so it is not a compile error.

Tip: Always check that a file opened successfully before using its size.

Practise all 20 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all C++ topics · All topics