very strange error

i have a program that just rewrites my numbers ( dont think about the practical use of this) and heres my input and ouput.

23 30 //input
2
23   30 // here i'm wondering why its adding 2 spaces
300 65
3
300 Éý;  65 // once the first number is bigger then 100 it starts displaying some random stuff between the numbers
23 30
2
23 Éý;  30 // and he keeps doing that ( same as first time but now with shit inbetween)


heres my code:
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
28
29
#include <iostream>
using namespace std;

int main()
{
	while(5==5){
	char inj[15],i[7],j[7],space=0x20;
	int p,k;
    cin.getline(inj,15);
	for (p=0;p<15;p++)
	{
		if(inj[p]==' ') 
		{
			for (k=0;k<(p+1);k++) 
			{
				i[k]=inj[k]; 
			}
			for (k=0;k<(15-p);k++)
			{
				j[k]=inj[k+p];
			}
			cout << p << endl;
		}
	}
	cout << i << space << j << endl;
	}
	system("pause");
    return 0;
}

can someone please tell me why hes doing that and how to solve it.
Last edited on
I'm guessing you overwrote/forgot the termination character that is required for C-strings. My advice: ditch the char* and go with std::string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
while (true) {
    char inj[15], i[7], j[7], space = 0x20;
    cin.getline(inj, 15);
    for (int p = 0; p < 15; p++){
        if (inj[p] = ' ') {
            for (int k = 0; k < (p+1); k++)
                i[k] = inj[k]; // Possible faults due to accessing outside of array bounds.
            for (int k = 0; k < (15-p); k++)
                j[k] = inj[k+p]; // Possible faults due to accessing outside of array bounds.
            cout << p << endl;
        }
    }
cout << i << space << j << endl; // This is undefined. You can't print the whole array at once.
}
Last edited on
but a string isnt an array of characters so i cant find the space in it or is it?
@gelatine

I believe most of your problems arise from the fact that you are trying to access data that is outside of your array
1
2
3
4
5
6
7
8
9
for (k=0;k<(p+1);k++) 
{
	i[k]=inj[k]; // k can be 0 to 15, but array i is i[7]
}
for (k=0;k<(15-p);k++)
{
	j[k]=inj[k+p]; // k can be 0 to 15+p , but array j is j[7]
}
cout << p << endl;
A string is a container type. You can always check it's elements to see if they contain a value.
C++ strings allow for 'char' access just like C-strings:

1
2
	std::string myString("Boobies!");
	std::cout << myString[3];

Output:
b
ive changed the size of i and j to 15 but i still have the same problem.
When I run this program, i and j have garbage all the way up to the end of the 15 bytes at the start of the program and you're not setting a NUL to the end of the copied data.

You may want to memset your arrays.

Simply:

memset( inj, 0, sizeof(inj));

i is getting a space put in at the end of the string and j is getting a space put in at the front.

That is why there is three spaces and not one.
Last edited on
Topic archived. No new replies allowed.