0
0
C++programming~10 mins

Type casting in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert the integer 10 to a float.

C++
int a = 10;
float b = [1];
std::cout << b << std::endl;
Drag options to blanks, or click blank then click option'
Astatic_cast<float>(a)
B(int)a
Cfloat(a)
Da
Attempts:
3 left
💡 Hint
Common Mistakes
Using C-style cast like (int)a which does not convert to float.
Assigning integer directly without casting.
2fill in blank
medium

Complete the code to cast a double to an integer using C-style cast.

C++
double pi = 3.14159;
int x = [1];
std::cout << x << std::endl;
Drag options to blanks, or click blank then click option'
Astatic_cast<int>(pi)
B(int)pi
Cint(pi)
Dpi
Attempts:
3 left
💡 Hint
Common Mistakes
Using int(pi) which is a functional-style cast instead of C-style.
Assigning double directly to int without cast.
3fill in blank
hard

Fix the error in the code by correctly casting a void pointer to an int pointer.

C++
void* ptr = nullptr;
int* iptr = [1];
std::cout << iptr << std::endl;
Drag options to blanks, or click blank then click option'
Areinterpret_cast<int*>(ptr)
Bstatic_cast<int*>(ptr)
C(int*)ptr
Ddynamic_cast<int*>(ptr)
Attempts:
3 left
💡 Hint
Common Mistakes
Using dynamic_cast which only works with polymorphic types.
Using C-style cast which is less safe.
4fill in blank
hard

Fill both blanks to create a map from string lengths to strings, filtering only strings longer than 3 characters.

C++
std::map<int, std::string> length_map;
for (const auto& word : words) {
    if (word.[1] > 3) {
        length_map[static_cast<int>(word.[2])] = word;
    }
}
Drag options to blanks, or click blank then click option'
Aword.length()
Bsize()
Clength()
Dword.size()
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect member functions or missing static_cast for int conversion.
Using word.length() inconsistently.
5fill in blank
hard

Fill all three blanks to create a vector of floats from a vector of ints by casting each element.

C++
std::vector<int> nums = {1, 2, 3, 4};
std::vector<float> floats;
for (auto [1] : nums) {
    floats.push_back([2]);
}

float first = floats[[3]];
Drag options to blanks, or click blank then click option'
Anum
Bstatic_cast<float>(num)
C0
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong loop variable name.
Forgetting to cast inside push_back.
Using wrong index to access vector element.