SRL Archive - C/C++ Help and Tutorials

C++ Homework Help Needed


Elip007

2013-03-13 15:11:17

I have received an assignment for C++ and I am not able to figure it out. Just started C++ so it's not simple for me. I keep receiving errors everywhere and would like some one to help me out and possible comment the steps so I could understand the thought process.

Write a function that accepts a pointer to a C-string as an argument and returns the number of words contained in the string.
For instance, if the argument is "Four score and seven years ago" the function should return the number 6.
Demonstrate the function in a program that asks the user to input a string and then passes it to the function.
The number of words in the string should be displayed on the screen.
Optional Exercise: Write an overloaded version of this function that accepts a string class object as its argument.

superuser

2013-03-13 15:25:53

What have you done so far? I don't think people will solve your homework out of the box :)

Elip007

2013-03-13 22:15:03

Haha some have and I am very thankful for that! I don't have it with me at the moment. Will edit it in when I get the chance.

mcbain

2013-03-14 15:56:32

Wrote this really quick, so don't beak me :) but it counts the words, for a given string. I used "Four score and seven years ago" which is 6 words long. Which is the output i get :) Not commented, but if need be i can edit and comment the lines.

C++ code:

#include <cstring>
#include <string>
#include <iostream>

int stringsize(char*);
using namespace std;

int main()
{
char* cstring = "Four score and seven years ago";
int numofwords;
numofwords = stringsize(cstring);
cout << numofwords << endl;


return 0;

}
int stringsize(char* cstr)
{
int pos,sizeofstr;
sizeofstr = 0;
string copy;
string cplusstr(cstr);
while ((pos = cplusstr.find(' ')) != -1)
{
pos = cplusstr.find(' ');
copy.assign(cplusstr,0,pos);
cplusstr.erase(0,pos+1);
copy.erase(0,pos);
sizeofstr = sizeofstr + 1;
}
int length = cplusstr.size();
char* cstring = new char[length + 1];
strcpy(cstring,cplusstr.c_str());
if(cstring != NULL) //no whitespace left but there is still a word
{
sizeofstr = sizeofstr + 1;
}
return sizeofstr;
}