1

I am writing a program to generate a random 16-digit number. My approach is using a character array to store random numbers one by one. Ultimately, I want to convert this character array into a string. How do I do that?

I tried converting it directly to a string but the output gives some weird characters after the 16-digit number when I output it onto the screen.

#include <iostream>
#include <string>
using namespace std;

int main(){
  char acct_num[16];
  for(int x = 0; x < 16 ; x++){
      acct_num[x] = rand()%10 + '0';
    }
  acct_num[16] = '\0';

  cout<<string(acct_num)<<endl;

}

I just want the 16-digit number as a string.

3 Answers 3

6

You have run off the end of your array. A c-style string is called a character string (rather than a character array). You have correctly added the '\0' at the end of the string, but you have written to 17 bytes, so you just need to make the char buffer 17 bytes long so that you can have 16 bytes for your digits.

Make the array 17 chars long:

#include <iostream>
#include <string>
using namespace std;

int main(){
  char acct_num[17];
  for(int x = 0; x < 16 ; x++){
    acct_num[x] = rand()%10 + '0';
  }
  acct_num[16] = '\0';

  cout<<string(acct_num)<<endl;

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

1 Comment

That fixed it. Thank you!
2

Also, you can explicitly specify the size to avoid a '\0' at the end:

#include <cstdlib>
#include <iostream>
#include <string>

int main()
{
  char acct_num[16];
  for (int x = 0; x < 16; ++x) {
    acct_num[x] = rand() % 10 + '0';
  }

  std::cout << std::string(acct_num, 16) << "\n";
}

Comments

1

In this case, I would suggest using only std::string by itself and not use a char[] at all:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

int main(){
    std::srand(std::time(0));

    std::string acct_num;
    acct_num.resize(16);

    for(int x = 0; x < 16 ; x++){
        acct_num[x] = std::rand()%10 + '0';
    }

    std::cout << acct_num << std::endl;
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.