C++/follow up to string manipulation
Expert: Eddie - 9/29/2004
QuestionHi
Your previous answer was very helpful and it did solve the problem. But I have trouble understanding the logic behind your code, especially the part when inputstr() and outstr() are used to put * between each letter of the string. Could you explain it to me how that worked. To freshen your mind, I typed in the code below.
By the way, I would also like some advice on this problem:
Create a 10 x 10 times table, with a title row and colums. Create 3 identical tables using nested for, while and do..while structures.
Thank you again
char inputstr[30], outputstr[60];
int len=0,i=0,j=0,k=0;
printf("Enter a string: \n");
scanf("%s",&inputstr);
len = strlen(inputstr);
j=0;
k=0;
for(i=0;i<2*len-1;i++)
{
if(i%2==0)
{
outputstr[j++]=inputstr[k++];
}
else
{
outputstr[j++] = '*';
}
}
outputstr[j++]='\0';
printf("The output string is %s",outputstr);
AnswerHello katrina,
I think that you are overcomplicating your problem here. You take input from the user, then print out each letter with a '*' in between. In order to do this, you only need to print out each array sub, then a '*'. One problem I did see above was that since we are accepting a string input into an array, theres no need to pass scanf the address of the array because the name of the array is already a pointer:
// in main
char inputstr[30] = {0};
unsigned int i;
printf("Enter a string:\n");
scanf("%s", inputstr);
for(i = 0; i < strlen(inputstr); i++)
{
// print out each letter
printf("%c", inputstr[i]);
// print out a '*'
printf("*");
}
As you can see, thats a lot easier and cleaner, and accomplishes the same thing. As for you other problem, I'm not too clear on what you aim to do. If you could please be a little bit more specific I would be glad to try and help.
I hope this information was helpful.
- Eddie