Expand function

I am working on expand function, that asks to write a C++ command-line program that includes a main function and an expand function. The main function should ask the user to input a string and a character, output the original string, call the expand function, then output the expanded string. Funciton expand should not contain any cin or cout statements.
The signature of expand is
void expand(char str[], char mark);

Before expansion: banana
After expansion: ba na na

(My issue is it print out:
Before expansion: banana
(space)After expansion: banan )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void expand(char str[],char mark)
{
	cout<<sizeof(str)<<endl;
	for(int i=0;i<=sizeof(str);i++)
	{
		if(str[i] == mark)
		{
			cout<<" ";
		}
	}
}

int main ()
{
	char letter;
	string astring;
	cout<<"Enter a string: ";
	cin>>astring;
//	vector<char>word;
	char *word = new char [astring.size()];
	for(int i=0;i<astring.size();i++)
	{
//		word.push_back(astring[i]);
		word[i] = astring[i];
	}
	if(word == 0)
		cout<<"Error!"<<endl;
	
	cout<<"Enter a character that exists in the string: ";
	cin>>letter;
//	for(int k=0;k<=word.size();k++)
//	{
//		cout<<word[k];
//	}
	cout<<"Before expansion: "<<word<<endl;
	
	expand(word,letter);
	
	cout<<"After expansion: ";
	for(int j=0;j<=sizeof(word);j++)
	{
		cout<<word[j];
	}
	cout<<endl;

	delete [] word;
    return 0;
}
One thing I see is that you are using sizeof() to get the size of a pointer to char. That gives you the size of the pointer, not the C-string. Use strlen() instead.

And what is expand supposed to do? Put a space after every character "mark" in the given string?
That gives you the size of the pointer, not the C-string. Use strlen() instead.

Thank you!
And what is expand supposed to do? Put a space after every character "mark" in the given string?

Yes. Putting a space or tab after every appearance of the "mark" that the user has inputted, must be in the string.
Last edited on
How are you supposed to modify the C-string you are passing in? Re-allocate memory or something? Or is the function only suppose to print the expanded string?
The function is suppose to print the expanded string, re-allocate memory is only my thought of solving this problem, so it may not be right at all. But it seems right to me in some sense, but when I run the program after fixing the strlen(), it prints out some spaces in the very beginning of the line like:


Before expansion: banana
    After expansion: banana


instead of wanted:


Before expansion: banana
After expansion: ba na na

Topic archived. No new replies allowed.