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

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