0

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.

  • 3
    Lessons (1) NEVER skimp on buffer size; (2) `scanf ("%s", letters);` is no safer than `gets()`, see [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/q/1694036/3422102). You must ALWAYS use a *field-width* modifier when filling a character array (e.g. `scanf ("%5s", letters)`) and (3) you must ALWAYS validate input succeeded (e.g. `if (scanf ("%5s", letters) != 1) return 1;` (of course adjust the numbers when you fix the problem with Rule (1) above). – David C. Rankin Jul 05 '21 at 01:30

2 Answers2

3

wordNow is not null terminated, leading to the output you are seeing. Also, results is not initialized.

Brady Dean
  • 3,378
  • 5
  • 24
  • 50
2

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106