You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何每30个字符拆分字符串并换行?附现有C++代码求易懂方案

How to Wrap a String Every 30 Characters in C++

Hey there! Looks like you're trying to split a string into new lines every 30 characters, and your current code isn't quite hitting that mark. Let's get this sorted out for you.

First, let's break down what your existing code does right now:

  • The first loop just prints numbers 0 to 29 with spaces, which doesn't contribute to your string-wrapping goal at all.
  • The second loop prints each character of your input string with a space, but there's no logic to insert a newline after every 30 characters.

Here's a corrected, easy-to-follow version of your code that does exactly what you need:

#include<iostream>
#include<string>
using namespace std;

int main(){
    string inputStr;
    cout << "Enter Sentence: ";
    getline(cin, inputStr);

    for (int i = 0; i < inputStr.length(); i++) {
        // Print the current character from your input
        cout << inputStr[i];
        
        // Check if we've just printed the 30th, 60th, etc. character
        // We use (i + 1) because we start counting from 0, so i+1 gives the 1-based position
        // The extra check avoids adding an unnecessary newline at the very end of the string
        if ((i + 1) % 30 == 0 && i != inputStr.length() - 1) {
            cout << endl;
        }
    }

    return 0;
}

Key details to note:

  • We loop through each character of your input string directly, no extra unnecessary loops.
  • The condition (i + 1) % 30 == 0 triggers a newline after every 30 characters from your original input.
  • The && i != inputStr.length() - 1 part ensures we don't print an extra blank line if your string's length is exactly a multiple of 30.

If you want to keep the space between each character like your original code had, just adjust the print line and keep the same logic:

#include<iostream>
#include<string>
using namespace std;

int main(){
    string inputStr;
    cout << "Enter Sentence: ";
    getline(cin, inputStr);

    for (int i = 0; i < inputStr.length(); i++) {
        cout << inputStr[i] << " ";
        if ((i + 1) % 30 == 0 && i != inputStr.length() - 1) {
            cout << endl;
        }
    }

    return 0;
}

This version will add a space after every character and wrap to a new line once 30 input characters have been printed. No complicated methods required!

内容的提问来源于stack exchange,提问作者noobiee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:10:23