I want to make a program that when the user enters AB1245 and have the program change it to AB 12345 (an added space between 2nd and 3rd character)
char Bilnr[9];
for (i = 8; i < 3; i--) {
Bilnr[i++]=Bilnr[i];
}
As I understand this, this program will start with Bilnr[9] and set it to the value of Bilnr[8].
Then set Bilnr[8] to the value of Bilnr[7].
But it doesn't move any of the values. It simply prints AB1245.
One thing I notice is that if your loop ever actually executes, it would be infinite
for (I=8; I<3; I--) {
Bilnr[I++]=Bilnr[I];
}
I++ doesn't mean I+1 rather, it means I = I+1
but your loop won't execute, because your condition, I<3 will be false from the get-go when you initialize I with I=8
You're also never setting I[2] to be a ' '
you also also have to realize that arrays start at 0, so Bilnr[0] == 'A'
try
for(int i = 8; i > 2; i--)
{
Bilnr[i] = Bilnr[i-1];
}
Bilnr[2] = ' ';
It prints the same, because the loop never runs. The loop condition is wrong, it should be I>3 to start. The for loop works as follows:
for (initialization; condition-that-has-to-be-true; optional-increment-decrement) {
}
Also remember C/C++ arrays start counting at 0, not 1.
To fix your complete code:
char Bilnr[9] = "AB12345";
for (I=7; I>2; I--) {
Bilnr[I]=Bilnr[I-1];
}
Then you have AB112345. All you need then is put in the space:
Bilnr[2] = ' ';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With