所以我正在制作一个程序,它可以让你输入一个句子,程序会计算句子中有多少个单词。我似乎无法让程序让我输入字符串。我需要在 cin 中包含指针吗?
#include <cstring>
#include <string>
#include <iostream>
int stringsize(char*);
using namespace std;
int main()
{
char* cstring; //pointer
cout << " Please enter phrase to count number of words: ";
cin.get(cstring);
int numofwords;
numofwords = stringsize(cstring);
cout << numofwords << endl;
system("pause");
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;
}