2016-05-09 86 views
-2

所以我试图在屏幕上使文本滚动,例如;^h - 他 - HEL - 地狱 - 你好我的substr()不能按预期工作

#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! 

请帮帮我!

+0

通常你需要发送一个字符来移动光标回到行的开头,例如:'\ r'。 – tadman

+1

大家知道,C++ 11有一个标准的'std :: this_thread :: sleep_for'函数。并且0100是4的八进制文字,而不是100的值。 – chris

+0

否#include '? – CinCout

回答

4

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

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

+0

谢谢!我虽然(x,x)只会做x – user3051697

1

这是因为substr()函数需要两个参数,即要打印的字符串的起始位置和大小。因此,在第一次迭代时执行substr(0,0)并在另一次迭代时substr(1,1)输出'e' 第3次迭代substr(2,2)输出“lc” substr(3,3) - “com” 等.....

2

您正在使用substr错误。您应该用1替换第二个参数(x)。第二个参数是您想要“获取”的字符数。所以text.substr(x,1); ,你会全部设置:)