Saturday, May 22, 2010

Inserting blank spaces between digits in pure C Programming?

I have to write a c program that will take any number and output that same number with 3 spaces between each digit. I know I need to use a while loop. How do you make it calculate how many digits are in the number? With scanf I know its like scanf("%d", %26amp;number) and that will read input and assign it to number. can you make it read each digit individually and assign it its own variable.





If a user inputs the number 123456789, I need the output to be


1 2 3 4 5 6 7 8 9


Any ideas?


I can not use an array. I can use while loops, just not arrays.


help? please.

Inserting blank spaces between digits in pure C Programming?
Since you mentioned there should be no array here is some change in my earlier code which could be of help


I have not run it. some debugging may be required





char *nst;


scanf("%s", str);





ln=strlen(str);


nst=malloc(ln*4);


/* since three spaces are required after each char */





for (i=0; i%26lt;ln; i++)


{


sscanf (str, "%c", nst++);


for(k=0;k%26lt;3;k++,nst++)


{


*nst=" ";


}


}


*nst='\0';


printf("%s",nst);


/*


if you wish to use str (the original string) itself then you could change the code accordingly


*/
Reply:keep scanfing your number with %c instead of %d getting one character at a time until you hit the end of your string. So





char number;


scanf("%c", %26amp;number);





while(number) {


printf(" %c", number);


scanf("%c", %26amp;number);


}





OT:


I assumed he was reading in a number off stdin so all he had to do was just read it one character at a time instead of parsing it as an int.





If its an int he gets then yours is the only way that would work.
Reply:Are you being required to convert it to a number? Are you being told that you can't use an array to do the homework? It's pretty easy to leave it as ascii and do it, but if you have to take it as a number you'll need to divide it and print. I'd probably choose to use a recursive function something like this:





int divideit(int num)


{





if(num %26gt; 10){


num /= 10;


num = divideit(num);


}


printf("%d ", num);


}





You'll have to debug, but that should get you started.





Bob:


Humorous, you can't scan characters out of an integer, and he's been told that he can't use an array where he could use an sscanf or other things. Scanf works with standard input (you'd need to use sscanf to point to something other than what standard input points to). He could use a while statement rather than recursive programming, but a little bit of time with gdb looking at the stack and understanding recursion will do him good later in his programming career. I purposely didn't debug or give a full answer so he could still learn from the homework, but I don't think it fair to mislead him either.


No comments:

Post a Comment