c++ - 用于显示字符串 | 的每个字符的 for 循环C++

标签 c++ compilation

我想知道如何控制字符串并从字符串中获取字符。
这是我的代码:

#include <iostream>
#include <string>

using namespace std;

int mainMenu();

int main() {
    mainMenu();
}

int mainMenu(){
    string introText = "Welcome... Let me know your name!";
    cout << "\t\t\t";
    for (int i = 0; i <= introText.length(); i++){
        unsigned controller = i + 1;
        cout <<introText.substr(i,controller);
    }
}


此输出如下:

    Wellcocomeome..me... e... Le... Let .. Let me. Let me k Let me knoLet me know et me know yot me know your me know your nme know your name know your name! know your name!know your name!now your name!ow your name!w your name! your name!your name!our name!ur name!r name! name!name!ame!me!e!!


正确的方向是什么?我该如何解决这个问题?

最佳答案

std::basic_string::substr用于提取字符串的一部分。如果你想打印字符串的每个字符,你可以只使用 std::basic_string::operator[]std::basic_string::at :

for (int i = 0; i < introText.length(); i++){
    cout <<introText[i]; // or cout <<introText.at(i);
}

关于c++ - 用于显示字符串 | 的每个字符的 for 循环C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21772717/

相关文章:

c++ - 如何使用 Cereal 序列化 json 对象而不将其包含在子对象中

compilation - 使用 LINK.EXE 和 C2.EXE 手动编译 VB6 项目

c++ - 错误 : ‘memset’ was not declared in this scope

rust - 在x86 macOS上交叉编译到i686

c++ - 扩展 GCD 算法

c++ - C 和 C++ 中使用的不同版本的 exec 是什么?

c++ - getLocalBounds 替代文本对象? (SFML)

c++ - 这是 g++ c++14 支持中的错误吗?

php - 尝试用 PHP 编译 C 代码

.net - System.Data.SQLite.dll - 哪个版本以及如何编译?