line 9: If you want someone to type up to 20 characers then you have to define charString as 21 in order to allow room for the null string terminating character.
line 23: All you want here is to enter a single character, not an entire string. Similar to line 26.
lines 29-42: all you need here is just one loop to test each character in sentenceHolder1 for the character you enter on line 23 and possibly replace it with the replacement character.
int len = strlen(sentenceHolder1);
for(int i = 0; i < len; i++)
{
if( sentenceHolder1[i] == look_for_character )
sentenceHolder1[i] = replacement_character;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Stick to the program requirements and don't try to do fancy stuff. Your task is to code what the prof asked you to code, not to make up stuff on your own.
There isn't anything wrong with trying out various things on your own -- just don't hand any of it in as part of the assignment.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Any help with how to replace an instance of a character in the array with the first character of the array would be greatly appreciated :)
sentenceHolder1[i] = sentenceHolder2[0]; will replace a character in sentenceHolder1 with the first charcter in sentenceHolder2.
>>Yea I wasn't planning on handing that part in, my prof just suggested in one of our classes that it
>>was possible and I was wondering how you could do it because he won't tell me.
Yes it is possible. Hint: strstr() from string.h is your friend when working with charcter arrays. There are better ways when using c++ std::string class, but you probably have not gotton to those in your class.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
That's the same as I posted, but this:
for(index1=0; index1 < strlen(sentenceHolder1); index1++)
You don't want to call strlen() like that because it has to be executed on every iteration of the loop. Code it once as I did and just use that variable.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
List of things wrong with kaveyarrasan.k's effort:
- it's two years too late
- it's in C, not C++ (see the forum title)
- it has no code tags
- it uses void main
- it has a buffer overflow (<=25 steps off the end)
- the for loop to "search" for the char to replace serves no purpose. Just use a[n] directly.
- as the input buffer is un-flushed, the %c scanf will read the \n left behind by the %d scanf earlier.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953