Joel G Mathew
Joel G Mathew

Reputation: 8061

Unexpected output (C strings and characters)

I'm just starting off with characters and arrays. I wrote some code to generate a string of certain random and non-random characters. Well, actually it's supposed to generate bargain codes for Dominos pizza. Ahem...

Anyway, this is the code, and I'm perplexed by lack of any output whatsoever. I compiled with gcc -Wall, and there's no warning or errors. So it's apparent that it's some fundamental structural aspect regarding strings.

I'd appreciate any insights regarding this.

Code:

#include <stdio.h>
#include <stdlib.h> 
#include "conio.h"
#include <time.h>


int genrandom(int,int);
char randAlph(void);
char letterize(int);
char randDigit(void);
char digitize(int);
void weaver(void);
void prtall(char[],int);


int main (void) {

    srand(time(0));  
    weaver();
    return 0; 
}



void weaver(void) {
  //BG5C?---1
    char word[10];
    word[0]='B';
    word[1]='G';
    word[2]='5';
    word[3]='C';
    word[4]=randDigit();
    word[5]=randAlph();
    word[6]=randAlph();
    word[7]=randAlph();
    word[8]='\0';
    prtall(word,8);
}

void prtall(char worder[],int len){       
    int i;
    for (i=0;(i=len);i++) {
      if ( worder[i] != '\0' ){
    printf("%c",worder[i]);
      }
    }
    printf("\n");
}   

int genrandom(int mino,int maxo) {
    int val=mino+rand()/(RAND_MAX/(maxo-mino)+1);
    return val;  
}

char randAlph (void){
  int val;
  char text;
  val=genrandom(0,26);
  text=letterize(val);
  return text;

}

char randDigit () {
    int val;
    char text;
    val=genrandom(0,9);
    text=digitize(val);
    return text;                            
}

char letterize(int num) {
  char letter='A'+num;
  return letter;
}

char digitize(int num) {
  char digit='0'+num;
  return digit;
}

Upvotes: 2

Views: 109

Answers (4)

Mike
Mike

Reputation: 49363

Your stuck in an infinite loop, the problem is with the for statement:

for (i=0;(i=len);i++) {

You want i<=len, not i=len. Your for loop right now is doing:

i = 0, i = 8
if '\0' != '\0'
i++ (i = 9)

Then when it goes to "check" the condition it really just resets i to 8

Upvotes: 1

unwind
unwind

Reputation: 399703

Since you through the trouble to 0-terminate your array, just print it with:

puts(word);

or

printf("%s\n", word);

to get the line-feed.

No need to loop yourself and print one character at a time.

Upvotes: 2

codaddict
codaddict

Reputation: 454912

for (i=0;(i=len);i++)

should be

for (i=0;i<=len;i++)

Upvotes: 5

Desert Ice
Desert Ice

Reputation: 4600

for (i=0;(i=len);i++)

Did you mean i <= len ?

i=len is an assignment, returns true if assignment succeeds.

So what happens is

i gets assigned the value of len, (which is successful) hence returns true.

Hence for loop condition gets satisfied.

What you need is

           for (i=0;i<=len;i++)

Upvotes: 1

Related Questions