1

OK、文字列が更新されるように、文字列を作成しようとしています。「hello」という文字列があり、「h」「he」「hel」「hell」「hello」のように更新したい

ので、私は持っています:

#include <iostream>
#include <string>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

using namespace std;

int main()
{
    system("title game");
    system("color 0a");
    string sentence = "super string ";

    for(int i=1; i<sentence.size(); i++){
        cout << sentence.substr(0, i) <<endl;
    }
    return 0;
}

コードは次のように返されます。

「す」「す」「すぺ」「すーぱー」

明らかに別の行ですが、最後の行を削除すると、文ビルダーが暴走します。「spupsppuepr sttrrtrsubstringsubstring」のようなものが表示されます

THE SAME LINEの文字列を更新できる方法はありますか? (そして完全に破壊しないでください)

4

3 に答える 3

3

各反復でキャリッジ リターン文字'\r'を出力して、カーソルを行頭に戻すことができます。

for(int i=1; i<sentence.size(); i++){
    cout << '\r' << sentence.substr(0, i);
}

または、各文字を順番に出力します。

for(int i=0; i<sentence.size(); i++){
    cout << sentence[i];
}

また、タイプライター効果を実現するために、ループの反復ごとに短い遅延を挿入することもできます。

于 2012-05-25T01:13:19.257 に答える
0

コードを実行すると、次のようになります。

./a.out
ssusupesupesupersuper super ssuper stsuper strsuper strisuper strinsuper string

これはまさにあなたがそうするように指示することです。endl と同じですが、改行はありません。すべての文字を繰り返さない場合は、部分文字列ではなく、文字列自体を反復処理する必要があります。

using namespace std;

int main()
{
    system("title game");
    system("color 0a");
    string sentence = "super string ";

    for(int i=0; i<sentence.size(); i++){
        cout << sentence[i];
    }
    return 0;
}
于 2012-05-25T01:13:19.500 に答える
0

私のアドバイス: を使用してWhile loopください。

#include <stdio.h>
#include <iostream>

int main() {
    system("title game");
    system("color 0a");
    char* sentence = "super string";

    while( *sentence ) std::cout <<  *sentence++;
    return 0;
}
于 2012-05-25T02:30:29.017 に答える