所以我正在製作一個程序,它可以讓你輸入一個句子,程序會計算句子中有多少單詞。我似乎不能讓程序讓我輸入字符串。我是否需要將指針包含在cin中?C++作業 - 計數字
#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;
}
你是什麼意思'我似乎不能讓程序讓我輸入字符串.'?當你嘗試給它輸入時會發生什麼? – 2013-03-27 20:10:26
[C++函數來計算字符串中的所有單詞]的可能的重複(http://stackoverflow.com/questions/3672234/c-function-to-count-all-the-words-in-a-string) – 2013-03-27 20:37:45