C++ string scan: count characters immediately following spaces in "Welcome to CuriousTab.com!" and return the count length.\n\n#include<iostream.h>\n#include<string.h>\nclass CuriousTab\n{\n char str[50];\n char tmp[50];\n public:\n CuriousTab(char s)\n {\n strcpy(str, s);\n }\n int CuriousTabFunction()\n {\n int i = 0, j = 0;\n while ((str + i))\n {\n if (*(str + i++) == ' ')\n *(tmp + j++) = *(str + i);\n }\n *(tmp + j) = 0;\n return strlen(tmp);\n }\n};\nint main()\n{\n char txt[] = "Welcome to CuriousTab.com!";\n CuriousTab objCuriousTab(txt);\n cout << objCuriousTab.CuriousTabFunction();\n return 0;\n}

Difficulty: Easy

Correct Answer: 2

Explanation:


Introduction / Context:
The routine scans a C-string and copies into tmp each character that immediately follows a space in str. It then returns the length of tmp. This tests pointer arithmetic and pre/post-increment order in a loop.


Given Data / Assumptions:

  • Input text: “Welcome to CuriousTab.com!”.
  • Loop condition: while current character is non-zero.
  • On seeing a space, post-increment advances i before reading the next character.


Concept / Approach:
We need each character after a space. In the sample text there are two spaces: between “Welcome” and “to”, and between “to” and “CuriousTab.com!”. Therefore, the characters copied are the first letters of the following words, namely 't' and 'C'.


Step-by-Step Solution:
1) Initialize i=0, j=0. 2) Traverse until null terminator. 3) When str[i] equals space, post-increment makes i point to the next character; that character is assigned to tmp[j++]. 4) For the two spaces, copied characters are 't' and 'C', so tmp becomes “tC”. 5) strlen(tmp) is 2, which is printed.


Verification / Alternative check:
Add another space in the source string; the count increases accordingly, confirming the algorithm.


Why Other Options Are Wrong:
1 undercounts spaces; 24/25 misinterpret the function as returning the whole string length; 0 would require no spaces or an empty string.


Common Pitfalls:
Misunderstanding post-increment usage; off-by-one when reading the character after the space; forgetting to null-terminate tmp.


Final Answer:
2

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion