C++ Code to Print Digits of a Number Separated by Spaces - Using English Postpositional Modifiers
C++ Code to Print Digits of a Number Separated by Spaces - Using English Postpositional Modifiers
This C++ code snippet demonstrates how to print the individual digits of a given integer, separated by spaces. We'll be using English postpositional modifiers for clarity in the code.cpp#include
int main() { int N; std::cin >> N;
std::string strN = std::to_string(N);
for (size_t i = 0; i < strN.length(); i++) { std::cout << strN[i]; if (i != strN.length() - 1) { std::cout << ' '; } }
return 0;}
Explanation:
- Include Headers: We include the
<iostream>header for input/output operations (like usingstd::cinandstd::cout) and the<string>header to work with strings.2. Get Input: The code prompts the user to enter an integer (N) usingstd::cin.3. Convert to String: The integerNis converted to a string (strN) usingstd::to_string(N). This makes it easier to iterate over each digit.4. Iterate and Print: We use aforloop to iterate through each character (digit) of thestrNstring: -std::cout << strN[i];prints the current digit. -if (i != strN.length() - 1)checks if the current digit is not the last digit in the string. If it's not, three spaces (' ') are printed after the digit usingstd::cout << ' ';. This ensures that spaces are only added between digits and not after the last one.
Key Points:
- Postpositional Modifiers: The code utilizes English postpositional modifiers (the condition within the
ifstatement) to control the addition of spaces after each digit, enhancing code readability.* String Conversion: Converting the integer to a string simplifies the process of iterating over individual digits.
This code provides a concise way to print the digits of an integer separated by spaces in C++, making it easier to visualize and process each digit individually.
原文地址: http://www.cveoy.top/t/topic/2n6 著作权归作者所有。请勿转载和采集!