You are here:

C++/follow up to string manipulation

Advertisement


Question
Hi
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);  

Answer
Hello 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.