0

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!

  • 6
    `password` is not 0 terminated so it will keep printing until it finds a 0 or crashes or whatever other undefined behavior happens. Do yourself a favor and learn to use `std::string` instead. – Retired Ninja Jul 12 '23 at 05:08
  • 6
    Please note: [your code isn't valid c++](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard?r=Saves_AllUserSaves) – πάντα ῥεῖ Jul 12 '23 at 05:11

2 Answers2

1

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.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
0

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];
    }
   
}
  • `char password[n];` -- This is not valid C++. Arrays in C++ must have their size denoted by a compile-time constant, not a runtime variable. Dynamic arrays are done in C++ by using `std::vector`. --> `std::vector password(n);` – PaulMcKenzie Jul 12 '23 at 08:00