The weirdest thing I have ever seen working on console *SOLVED*

I was about to make a simple game on console. I was a surprise on what I saw.

1.The whole console sparkles

2.Player doesn't move correctly. Some times he "jumpes" to the second line even doe I have only moved right/left. There are other bugs too.

3.While player moves over, some text starts to be drawn. First, while going only right, it draws "cls". Further, It draws some more text that looks like a script or something. Eventually, It goes mad! It draws the text by it self, and it beeps (probably cause it draws chr(7) sometimes)!

4.When I am at the beginning, if I go any further up or left, program ends.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <conio.h>
#include <string.h>
using namespace std;

int keyboard_key() {if (kbhit()) {return getch();} else {return 0;} }

int main()
{
    int x=0;
    int y=0;
    int key;
    char plr=2;
    cout<<"You use arrow keys to move\nReady?\n";
    system("pause");
    while (1) {
          key=keyboard_key();
          if (key==77) {x+=1;} 
          if (key==75) {x-=1;} 
          if (key==72) {y-=1;} 
          if (key==80) {y+=1;}
          cout<<string(" ",y*60)<<string(" ",x)<<plr;
          system("cls");
          }
    system("PAUSE");
    return 0;
}

It looks like a perfect code.
Whats wrong? o_O
Last edited on
I wouldn't exactly call it perfect... For one thing, I don't think this will do what you think it does:
string(" ",y*60) <.....> string(" ",x)
The (char* s, int n) constructor takes the n first characters of *s. I think you wanted the (int n, char* s) constructor instead.

Secondly, system() calls are bad. Find a different way to clear the screen and pause. There are many topics about it on the forum!
I'm relatively new to C++, and I know system() stuff are not good, but I'm not so experienced enough to create a code by my self. I have some examples that I can use, but I just wanted the code to be short.

Also, I don't get this part:
The (char* s, int n) constructor takes the n first characters of *s. I think you wanted the (int n, char* s) constructor instead.

Does this mean I use string() function like this: string(n,str)?
I have tried that way, but the error says its string(str,n)

bump
http://cplusplus.com/reference/string/string/string/
string ( size_t n, char c ); Content is initialized as a string formed by a repetition of character c, n times.

In your case it will be string(x, ' ')
*facepalm*

You people were right all the time.
it's string(number,character) instead mine string(string, number)

Thank you everyone. i fixed it.
Topic archived. No new replies allowed.