如何编写C++程序实现文件字符按每10个换行且字符间隔两空格输出?
Solution for Formatted File Character Output
Got it, let's tweak your code to hit all your requirements: two spaces between every character, and automatic line breaks after 10 characters per line. Here's the breakdown and fixed code:
Issues with the Original Code
- No counter to track how many characters have been printed on the current line, so we can't handle the 10-character limit
- Unnecessary logic for handling spaces (your requirement treats all characters the same, so we don't need special cases)
- Missing line break functionality once the 10-character limit is reached
Fixed Code
#include <iostream> #include <fstream> using namespace std; // If you defined SPACE as a constant, keep it here; otherwise, you can remove this line const char SPACE = ' '; int main() { ifstream inFile("your_input_file.txt"); // Replace with your actual file path char textWritten; int currentLineCharCount = 0; cout << "Characters read from file are: " << endl; // Loop only while we successfully read a character from the file while (inFile.get(textWritten)) { // Print the current character cout << textWritten; currentLineCharCount++; // Add two spaces if we haven't hit 10 characters yet if (currentLineCharCount < 10) { cout << " "; } else { // Hit the 10-character limit: print a new line and reset the counter cout << endl; currentLineCharCount = 0; } } // Optional: Add a final new line if the last line didn't end with one if (currentLineCharCount != 0) { cout << endl; } inFile.close(); return 0; }
Key Improvements Explained
- Character Count Tracking:
currentLineCharCountkeeps tabs on how many characters we've printed in the current line. Once it hits 10, we print a newline and reset the counter. - Proper File Reading: Using
while (inFile.get(textWritten))ensures we only process characters that were successfully read, avoiding the edge case where the original code might reprocess the last character. - Consistent Separation: Every character gets followed by two spaces (unless it's the 10th character in the line, where we print a newline instead).
- Clean Final Line: The extra check at the end adds a newline if the last line had fewer than 10 characters, so your output doesn't end mid-line.
内容的提问来源于stack exchange,提问作者alexductm
相关产品推荐
相关产品推荐

