2012-05-25 2 views
1

좋아요, 그래서 문자열이 업데이트되어 문자열이 업데이트됩니다. 정렬의 당신이 "안녕하세요"문자열을 가지고 있고 그것은 다소 그래서C++에서 반복을 통해 문자열 업데이트

"시간" "그는" "그러는" "지옥" "안녕하세요"와 같은 자체를 업데이트 할 것처럼, 내가 가진 :

#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; 
} 

내가 마지막 라인을 제거 할 때 " 이의"SU " "SUP " "공중으로 " "슈퍼 "다른 라인에 분명히

하지만이 문장 빌더 그냥 간다

: 코드처럼 반환 광포합니다. "spupsppuepr sttrrtrsubstringsubstring"과 같은 무엇인가가 튀어 나옴

어쨌든 내가 같은 줄에 문자열을 업데이트 할 수 있습니까?

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

하거나 출력 순서로 각 문자 : 줄의 시작 부분으로 커서를 반환

+2

"go beserk"는 과장입니다. 단지 줄 바꿈없이 똑같은 것을 인쇄합니다. –

+0

'conio'는 더 이상 사용되지 않으며'system'은 각각'SetConsoleTitle'과'SetConsoleTextAttribute'로 대체 될 수 있습니다. 필자가'stdio.h'와'stdlib.h'는'cstdio'와'cstdlib'이어야하고,'namespace std'를 사용하는 문장, 특히 전역 문장은 나쁘다. – chris

답변

3

당신은 각 반복에서 캐리지 리턴 문자 '\r'를 인쇄 할 수있다 (그리고 완전히 파괴하지)

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

타이프라이터 효과를 얻기 위해 각 루프 반복마다 짧은 지연을 삽입하는 것이 좋습니다.

+1

오, 이런 ... 도와 줘서 고마워. : P –

0

이 코드를 실행하면이를 생성합니다

슈퍼 ssusupsupesupersuper
./a.out ssuper stsuper strsuper strisuper strinsuper 문자열

이것은 당신이 그것을 말해 정확히이다. 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; 
} 
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; 
} 
+0

이것은 실제로 같은 코드 비트가 아닙니다. 이것은'std :: string'이 아닌'char *'를 사용합니다. 또한,'(* sentence ++)'를 사용하는 것은 여러분이하는 일을 정확히 알지 못한다면 꽤 미친 짓이다. – Falmarri