Reputation:
the code is supposed to output all possible word combinations without any whitespace but with this method, it gives me whitespace
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char letters[6];
int on = 0;
int results;
printf("input the words all together: ");
scanf("%s", letters);
if (strlen(letters) == 6) {
for (int i = 0; i <= 6; i++) {
for (int j = 0; j <= 6; j++) {
for (int k = 0; k <= 6; k++) {
for (int l = 0; l <= 6; l++) {
for (int m = 0; m <= 6; m++) {
for (int n = 0; n <= 6; n++) {
char wordNow[6] = {
letters[i],
letters[j],
letters[k],
letters[l],
letters[m],
letters[n]
};
printf("%s\n", wordNow);
results = results+1;
}
}
}
}
}
}
}
printf("%d", results);
return 0;
}
This code is supposed to take in 6 characters and produce all possible combinations using those characters. When I use that method, the combinations end up repeating and gives me whitespace.
My old method that works but adds whitespace is:
printf("%c %c %c %c %c %c\n",
letters[i], letters[j], letters[k],
letters[l], letters[m], letters[n]);
If anyone could help, I would appreciate it.
Upvotes: 0
Views: 52
Reputation: 57013
You'll need to null terminate your string if you plan to print it, since printf
will keep iterating over the characters in the string until it hits the null terminator:
char wordNow[7] = {
letters[i],
letters[j],
letters[k],
letters[l],
letters[m],
letters[n],
'\0' // <-- added
};
int results;
should be int result = 0;
as Brady points out.
You might want to run your loops up to <
rather than <=
if you want to omit null terminators.
Upvotes: 2
Reputation: 3573
wordNow
is not null terminated, leading to the output you are seeing. Also, results
is not initialized.
Upvotes: 3