Insert symbols at a specified position
I want to create a program that when the user enters AB1245
and changes it to AB 12345
(added space between 2nd and 3rd chars)
char Bilnr[9];
for (i = 8; i < 3; i--) {
Bilnr[i++]=Bilnr[i];
}
As I understand it, this program will start with Bilnr [9] and set it to Bilnr [8].
Then we put Biln [8] on the value of Bilnr [7].
But it doesn't move any values. He just types AB1245
.
source to share
One thing I notice is that if your loop is ever executed it will be infinite
for (I=8; I<3; I--) {
Bilnr[I++]=Bilnr[I];
}
I++
does not mean I+1
, but meansI = I+1
but your loop won't execute because your condition I<3
will be false from get-go when initialized I
withI=8
You also never set I[2]
like' '
you should also understand that arrays start with 0
, so Bilnr[0]
=='A'
try
for(int i = 8; i > 2; i--)
{
Bilnr[i] = Bilnr[i-1];
}
Bilnr[2] = ' ';
source to share
This loop condition is wrong:
for (I=8; I<3; I--) {
Bilnr[I++]=Bilnr[I];
}
I
at least 3, so the loop never starts. You probably need one >
. You will also have an infinite loop if it ever starts, because you have I++
and I--
.
You want something like this:
for (I=7; I>1; I--) {
Bilnr[I+1]=Bilnr[I];
}
In addition, you will have to replace this space with a space, otherwise you will get "AB112345":
Bilnr[2] = ' ';
source to share
It prints the same thing because the loop never starts. The loop condition is wrong, it must start with I>3
. The loop works like this: for
for (initialization; condition-that-has-to-be-true; optional-increment-decrement) {
}
Also remember that C / C ++ arrays start 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 there you have it AB112345
. Everything you need fits into space:
Bilnr[2] = ' ';
source to share