I think the hardest thing about this assignment is that you have to remember that the inner loop doesn't know a thing about the outer loops testing condition, so you have to repeat it for it.
I would use two while loops, since you never know (conceptually at least) how many words there will be to separate.
With two while loops, it looks like:
Code:
int main()
{
int i, row, col;
char a[]="mary had a little lamb, it's fleece was white as snow";
char b[15][15];
i = row=col=0;
while(a[i]!='\0')
{ while(a[i] != ' ' ) {
b[row][col]= a[i];
col++;
}
b[row][col]='\0'; //add end of string marker char
which fails for two reasons:
1) The inner loop goes berserk when it reaches the end of the char array, and can't find a space - endless loop.
2) i, row, and col are either not being set up for the next letter, or not being reset for the next word. That's why your code wasn't working with the next word, by the way.
So:
Code:
int main()
{
int i, row, col;
char a[]="mary had a little lamb, it's fleece was white as snow";
char b[15][15];
i = row=col=0;
while(a[i]!='\0')
{ while(a[i] != ' ' && a[i]!='\0') {
b[row][col]= a[i];
col++;
i++;
}
b[row][col]='\0'; //add end of string marker char
row++; //get ready for a
col=0; //new row
i++;
}
All together:
Code:
#include<stdio.h>
void printIt(char b[][15], int rows);
int main()
{
int i, row, col;
char a[]="mary had a little lamb, it's fleece was white as snow";
char b[15][15];
i = row=col=0;
while(a[i]!='\0')
{
while(a[i] != ' ' && a[i]!='\0') {
b[row][col]= a[i];
col++;
i++;
}
b[row][col]='\0'; //add end of string marker char
row++; //get ready for a
col=0; //new row
i++;
}
printIt(b, row-1);
printf("\n\n\t\t\t press enter when ready");
(void) getchar();
return 0;
}
void printIt(char b[][15], int row) {
int i;
printf("\n\nwords are: \n");
for(i=0;i<row;i++)
printf("\n%s",b[i]);
}