我想知道如何控制字符串并从字符串中获取字符。
这是我的代码:
#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/