Trouble w/ a code that involves strings/char arrays.

I just want to start of by saying, no I'm not here to get answers to my HW, just wanted a few hints.

I have a project for class that is: Write a main procedure that calls deleteSubStr to delete the first “sea” from “she sells sea shells by the sea shore”. (we had to use all those function names that are in my program, but I'm not pasting that part because the way my prof. wrote it makes it look messy and confusing)

Here is the code. Error keeps pointing to the cout line in the int main() function.
I think I did something wrong with the deletesubstr function. Maybe it shouldn't be void?

Any hints/advice are appreciated.

P.S. I'm very new at C++ so please forgive my mistakes :(

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
#include <iostream>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;

const int MaxChars = 51; //Declare global constants.

int findSubStr(char [], char []); // Function prototypes.
void deleteSubstr(char [], char[]);

int findSubStr(char str[], char subStr[]) // FindSubStr function.
{
  int pos = -1, i, r, len1, len2;

  len1 = strlen(str);
  len2 = strlen(subStr);

  for (i=0; i<len1-len2; i++)
    {
      r= strncmp (str+i, subStr, len2);
      if (r==0)
        {
         pos=i;
         break;
        }
     }
     return(pos);
}

void deleteSubStr(char str[], char subStr[]) // deleteSubStr function.
   {
    char temp[MaxChars];
    int pos, len1;

    len1 = strlen(str);
    pos = findSubStr(str, subStr);
    strncpy(temp, str, pos-1);
    strcpy(temp+pos+3, str);
    strcpy(str, temp);
   }

int main() // Main function.
  {
   char str[MaxChars]= "She sells sea shells by the sea shore";
   char subStr[MaxChars]="sea";
   cout << deleteSubStr(str, subStr) << endl;
   return 0;
  }
Last edited on
You cannot cout a void. (Since your function's return type is void, it is the same thing.)

Your main function should look something like:

1
2
3
4
5
6
7
8
int main()
  {
  char str[MaxChars]="She sells sea shells by the sea shore";
  char subStr[MaxChars]="sea";
  deleteSubStr(str, subStr);
  cout << str << endl;
  return 0;
  }

That is, the deleteSubStr() function should modify its first argument.

Hope this helps.
Thanks for the tip!

Hmmm... Yeah, that was my concern as well. I wasn't sure what to do with it. I tried what you posted and the program ran but the output was: "She sells˙ø_ˇShe sells sea shells by the sea shore"

Probably something wrong with my substr functions.
Topic archived. No new replies allowed.