Why is this code outputting random garbage values at the end?

95 Views Asked by At

I was solving a problem on codeforces, but I keep running into unwanted garbage values as output. What can I do?

#include <iostream>
#include <string>
#include <conio.h>
#include <set>
#include <vector>
using namespace std;


int main(){


    int n, k;

    cin >> n >> k;

    char password[n];

    for(int i=0; i<n; i++){

        password[i]= 'a' +  i%k;

    }

    cout << password;

}

I can't figure out what to do. It's driving me nuts!

2

There are 2 best solutions below

0
Fantastic Mr Fox On

C-style strings have an issue which is that they must be null terminated. Aka the last character in the string must be \0 in order to tell where the string end is. This is because a string in c could just be a char* with no reference of the length. In c++ we prefer to use types provided by the c++ lib, like std::string. With std::string your code is much simpler:

    int n, k;
    std::cin >> n >> k;
    std::string password;

    for(int i=0; i<n; i++){
        password += 'a' +  i%k;
    }

    std::cout << password;

This code is much cleaner and fully conforms to the c++ standard.

1
pranjal khatri On

You can use string in this case and append to the string or if you want to stick to character you can do this.

#include <iostream>
#include <string>
#include <conio.h>
#include <set>
#include <vector>
using namespace std;

int main()
{

    int n, k;

    cin >> n;
    cin >> k;

    char password[n];
   
    for (int i = 0; i < n; i++)
    {

        password[i] = 'a' + i % k;
    }
    // cout<<password<<endl;
    for (int i = 0; i < n; i++)
    {
        cout<<password[i];
    }
   
}