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!

2
  • 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. Commented Jul 12, 2023 at 5:08
  • 6
    Please note: your code isn't valid c++ Commented Jul 12, 2023 at 5:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]; } } 

1 Comment

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<char> password(n);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.