2013-03-27 23 views
0

所以我正在製作一個程序,它可以讓你輸入一個句子,程序會計算句子中有多少單詞。我似乎不能讓程序讓我輸入字符串。我是否需要將指針包含在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; 
} 
+1

你是什麼意思'我似乎不能讓程序讓我輸入字符串.'?當你嘗試給它輸入時會發生什麼? – 2013-03-27 20:10:26

+0

[C++函數來計算字符串中的所有單詞]的可能的重複(http://stackoverflow.com/questions/3672234/c-function-to-count-all-the-words-in-a-string) – 2013-03-27 20:37:45

回答

1

使用std::string而不是char*。順便說一句,在您的實際代碼中,指針未初始化爲指向任何有效的內存位置。

std::string phrase; 
cin >> phrase; 

並將它傳遞給像phrase.c_str()這樣的函數。

1

問題是你沒有爲指針分配內存,你甚至沒有初始化它。

char* cstring = new char[256]; 

這應該修復它。

然後你會delete[] cstring;釋放分配的內存。


無論如何,這是C++,所以你應該儘量避免char*在任何時候使用std::string。性能不會有太大變化,在這種情況下,它甚至都不重要。

std::string str; 
std::cin >> str; 
int numofwords = stringsize(str.c_str());