我的substr()没有按预期工作

时间:2016-05-09 17:03:56

标签: c++ string substr

所以我试图在屏幕上滚动文字,例如; h - 他 - 赫尔 - 地狱 - 你好

#include <iostream>
#include <stdlib.h>


using namespace std;

int main()
{
    string text = "Welcome to the Password Vault!";
    int x;
    for (x = 0; x < text.length(); x++) {
        cout << text.substr(x,x);
        _sleep(0100);
    }
    return 0;
}

输出:

elccomome me toe to t to theto the Po the Pas the Passwthe Passworhe Password e Password Va Password VaulPassword Vault!assword Vault!ssword Vault!sword Vault!word Vault!ord Vault!rd Vault!d Vault! Vault!Vault!ault!ult!lt!t!!
Process returned 0 (0x0)   execution time : 1.961 s
Press any key to continue.

我想输出:

Welcome to the password vault!

请帮助我!

3 个答案:

答案 0 :(得分:4)

您不仅要更改起始位置,还要更改要获取的子字符串的长度,这是第二个参数。如果您只想一次获得一个字符,则第二个参数应为1

参见例如this substr reference了解更多信息。

答案 1 :(得分:2)

您正在使用substr错误。您应该将第二个参数(x)替换为1.第二个参数是您想要的字符数&#34;得到&#34;。 text.substr(x,1);也是如此 并且你将全部完成:)

答案 2 :(得分:1)

这是因为substr()函数需要两个参数,即起始字符串位置和要打印的字符串的大小。所以在执行substr(0,0)的第一次迭代中,在另一次迭代中,substr(1,1)打印&#39; e&#39; 第3次迭代substr(2,2)打印&#34; lc&#34; substr(3,3) - &#34; com&#34; 等等......

相关问题