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!
C-style strings have an issue which is that they must be null terminated. Aka the last character in the string must be
\0in order to tell where the string end is. This is because a string inccould just be achar*with no reference of the length. In c++ we prefer to use types provided by the c++ lib, likestd::string. Withstd::stringyour code is much simpler:This code is much cleaner and fully conforms to the c++ standard.