2017-02-18 21 views
-2

資本化的第一個字,我需要作出這樣的大寫每個句子的第一個字符的字符串的程序。例如,如果字符串參數是「你好。我的名字是喬。你的名字是什麼?「該函數應該操縱字符串,使其包含」你好。我的名字是喬。你叫什麼名字?「我不確定我做錯了什麼。有什麼建議麼?這裏是我的代碼:每個句子

#include<iostream> 
#include<cctype> 
#include<cstdlib> 

using namespace std; 

void capitalize(char sentence[], int const SIZE); 

int main() 
{ 
    const int SIZE = 1024; 
    char sentence[SIZE]; 

    cout << "Enter a string: " << endl << endl; 
    cin.getline(sentence, SIZE); 

    capitalize(sentence, SIZE); 

    system("pause"); 
    return(0); 
} 

void capitalize(char sentence[], int SIZE) 
{ 

    char *strPtr; 
    int count = 0; 

    sentence[0] = toupper(sentence[0]); 

    for (int i = 0; i < SIZE; i++) 
    { 
     strPtr = strstr(sentence[i], "."); 

     if (*strPtr == '.') 
     { 
        *strPtr = toupper(*strPtr); 
     } 
    } 

    while (sentence[count] != '\0') 
    { 
      cout << sentence[count]; 
      count++; 
    } 
} 
+1

什麼是你的代碼生成的輸出? – Fallen

+0

@Fallen我收到一條錯誤消息,說'strstr'未在此範圍內聲明。 – PAXlater

+1

一些提示:1)決定你是否正在編寫C或C++。 2)循環播放,直到達到SIZE最有可能超過用戶輸入的結尾。 –

回答

0

首先,正如評論中提到的,你不包括cstring。其次,你打電話strstrsentence[i],這是一個字符。你想要sentence + i這是一個char *。這將解決你的語法錯誤。

對於邏輯上的錯誤,它看起來像你想toupper時期。

strPtr = strstr(sentence[i], ".");應該找到開始i(含)字符串中的第一個週期。然後,你檢查是否strstr發現任何東西(如果不是,將返回null。如果找到你大寫strPtr序列,但strPtr仍然指向在目標字符串的第一個字符,也就是'.'。你應該尋找目標字符串". "然後增加一個過去,要找到下一個句子的第一個字母。不幸的是這樣做有strstr,因爲它不會告訴你多遠它看起來的字符串沒有安全的方式,因此它可能字符串簡單地". "結束,一個過去的數據會落在陣列上,您要麼需要手動迭代陣列,查找'.',然後檢查過去的數據,或者使用std::find來代替。

1
#include <cstring> // need this for strstr() 

void capitalize(char sentence[], int SIZE) 
{ 

    char *strPtr; 
    int count = 0; 

    sentence[0] = toupper(sentence[0]); 

    for (int i = 0; i < SIZE; i++) 
    { 
     strPtr = strstr(&sentence[i], "."); 
     //strPtr returns the pointer to 
     //the first occurence of "." after sentence[i] 
     if(strPtr==NULL) break; 
     if (*strPtr == '.') 
     { 
      // you really dont want to do this 
      //*strPtr = toupper(*strPtr); 
      // put the suitable code here and everything will work 
     } 
    } 
    //why the while loop? and count? 
    while (sentence[count] != '\0') 
    { 
      cout << sentence[count]; 
      count++; 
    } 
} 

你在做什麼是資本。「」但很明顯,你要予以資本化的下一個字符。所以你自己寫下那部分代碼,你會發現它更有價值。