I want to pass a text file using input redirection to my program as a command line argument. I would then like the words in this to be randomly printed and whitespace removed.

I would like to run the program as

foo <dict.txt

dict.txt will contain various words, such as

camel penguin tiger chicken

I can currently print the contents of dict.txt using

    char line[100];

    while(scanf("%[^\n]%*c", &line) == 1) {

this would output

camel penguin tiger chicken

I would like it to be random and whitespace removed such as


For the most part I am not sure how to approach it, I was thinking of putting it into an array and somehow randomizing it, or using regular expressions but I am not familiar with how to apply these.

Thanks in advance, I am a relatively new coder.

  • The dict.txt example you posted appears to be a single line. Is that the case, or is each word on a new line? Can you post a minimal reproducible example that reproduces the problem? – ggorlen Mar 12 at 1:17
  • 1
    Yes, you'd read the words into a static array or a dynamic one, then apply Fisher-Yates shuffle, then print the elements in the shuffled order without intervening spaces. – Antti Haapala Mar 12 at 1:48
  • 1
    Note that if you use redirection foo <dict.txt, the program gets no command line argument (other than the program name). Or you can get a command line argument foo dict.txt and then open and process the file. – Jonathan Leffler Mar 12 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.