Problem in an array of char - shows more than it should

Hello guys :) I am 17 years old and I am training for the olympiad. Amd while I was testing some codes, I came to this problem.

I have this 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
#include <iostream>
#include <string.h>
#include <fstream>

using namespace std;

ifstream f("input.txt");
ofstream g("output.txt");

int main()
{
    char sir[40],a[40];
    f>>sir;
    for(int i=0;i<strlen(sir);++i)
    {
        for(int j=0;j<strlen(sir);++j)
            a[j]=sir[j];
        for(int j=i;j<strlen(sir);++j)
            a[j]=a[j+1];
       for(int j=0;j<strlen(a);++j)
            g<<a[j];
       g<<'\n';
    }
    f.close();
    g.close();
    return 0;
}



This program make a copy of the source array, then it removes each character and shows the obtained array.

and when i insert "abcdefghijkl"

it should show this:
"
bcdefghijkl
acdefghijkl
abdefghijkl
abcefghijkl
abcdfghijkl
abcdeghijkl
abcdefhijkl
abcdefgijkl
abcdefghjkl
abcdefghikl
abcdefghijl
abcdefhjijk

"

But it shows some extra values:
"
bcdefghijklmþþ(
acdefghijklmþþ(
abdefghijklmþþ(
abcefghijklmþþ(
abcdfghijklmþþ(
abcdeghijklmþþ(
abcdefhijklmþþ(
abcdefgijklmþþ(
abcdefghjklmþþ(
abcdefghiklmþþ(
abcdefghijlmþþ(
abcdefghijkmþþ(
abcdefghijklþþ(

"

Can you please tell me why is this happening?



Edit:

I have found the problem... but can someone explain it to me?

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 <string.h>
#include <fstream>

using namespace std;

ifstream f("input.txt");
ofstream g("output.txt");

int main()
{
    char sir[40],a[40];
    f>>sir;
    for(int i=0;i<strlen(sir);++i)
    {
        for(int j=0;j<strlen(sir);++j)
            a[j]=sir[j];
        for(int j=i;j<strlen(sir);++j)
            a[j]=a[j+1];
       a[strlen(sir)-1]='\0';
       g<<a<<'\n';
    }

    f.close();
    g.close();
    return 0;
}

Last edited on
Topic archived. No new replies allowed.