I coded a program to generate combinations of a string using the numbers 0 thru 9 and characters A thru Z and then have them written to a text file. The program works fine except I'm getting a space in the output text file that I don't want and did not intend. Needless to say I cant figure out were the problem is. I am thinking it is something to do with the arraySize variable being set to a value of 37. But if I set it to 36 then I get an "Array bounds overflow" error. I'm fairly new to programming and have not made it through a C++ programming book past working with loops and arrays yet. I could use some help in trying to figure out what I'm missing in the following code. I'm using Microsoft Visual Studio as my IDE.
You don't need 6 different arrays containing the same string. Do declare only one which will be indexed by your different indices a to f.
You may also want to declare the array 'const' like the array size because you never changes its content.
Question though, I don't know how to index the string into each indices of a to f. Sorry if this sounds like a stupid question. I just haven't gotten that far yet into the programming courses and books.
Now here is my next question. I keep getting a space in the output file. I cut the program down from 5 nested loops within the first loop to just one for testing purposes.
#include<iostream>
#include <fstream>
#include "stdafx.h"
#include<conio.h>
usingnamespace std;
int main()
{
ofstream myfile;
myfile.open("combinations.txt");
constchar array[37] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Loops
for (int a = 0; a <= 36; ++a)
{
for (int b = 0; b <= 36; ++b)
{
cout << array[a] << array[b] << endl;
myfile << array[a] << array[b] << endl;
}
}
myfile.close();
cout << endl << endl;
// Finish Up
cout << "Press any key to exit . . ." << endl;
_getch();
return 0;
}
Here is some of the output that I'm getting with the space.
1 2 3 4 5 6 7 8 9 10
ZW
ZX
ZY
ZZ
Z
0
1
2
3
4
I'm not sure what I'm missing in the code causing this space happen. I'm thinking it has to do with my initial string and the declared size of the array. I just haven't figured it out yet.
I have tried a using a variable that is equal to " " (space) but I can't seem to get the IDE to accept it has a valid variable and not get a syntax error. If I can figure this out I know I can put in an if statement that will make the program not write these lines of output to the text file.
A char-array has a special property. It terminates using character '\0' which is invisible and may look like a space on your output. Such an array is called a C-string. In fact the number of relevant characters in your C-string is 36 only. To avoid manual counting letters and digits try the following code: