/ / मुझे उपयोगकर्ता इनपुट लेने के बाद सी स्टिंग में शब्दों की संख्या वापस करने की आवश्यकता है - सी ++, सरणियां, फॉर-लूप, सी-स्ट्रिंग्स, आइसस्पेस

मुझे उपयोगकर्ता इनपुट लेने के बाद सी स्टिंग में शब्दों की संख्या वापस करने की आवश्यकता है - सी ++, सरणियां, लूप, सी-स्ट्रिंग, आइस्पेस

मुझे एक प्रोग्राम बनाने की ज़रूरत है जो उपयोगकर्ता से इनपुट लेता है और फिर स्ट्रिंग में दर्ज किए गए शब्दों की संख्या वापस करता है। मैं सरणी में उपयोगकर्ता इनपुट संग्रहीत करता हूं char words[256]; मेरे पास एक फंक्शन है countWords। हालांकि यह लूप होता है और अगर यह एक स्पेस का सामना करता है तो वह बढ़ जाता है। if(words[i] == "") यदि शून्य वर्ण तक पहुँच जाता है तो काउंटर बंद कर दिया जाता है। यह फिर लौटते हैं nSpaces + 1 पहले शब्द के लिए खाता है।

लेकिन मेरा आउटपुट इसके बजाय स्ट्रिंग में वर्णों की संख्या का उत्पादन करने के लिए लगता है। इसे कैसे सुधारा जा सकता है।

#include <iostream>
#include <cstdlib>
using namespace std;

//Function Prototype
int countWords(char words[]);

int main(){

char words[256];

cout << "Enter a sentence: ";
cin.getline(words, 256);

int word_num = countWords(words);
cout << "The number of words in a string is: " << word_num << endl;

system("PAUSE");
return 0;
}

int countWords(char words[]){
int nSpaces = 0;
//unsigned int i = 0;

/*while(isspace(words[i])){
i++;
}*/

for (int i=0; i<256; i++){
if(isspace(words[i])){
nSpaces++;
// Skip over duplicate spaces & if a NULL character is found, we"re at the end of the string
//while(isspace(words[i++]))
if(words[i] == "")
nSpaces--;
}
}
// The number of words = the number of spaces + 1
return nSpaces + 1;
}

आउटपुट है:

Enter a sentence: Yury Stanev
The number of words in a string is: 7

उत्तर:

जवाब के लिए 2 № 1

जब आप अशक्त चरित्र को प्राप्त करते हैं तो आप लूप को रोकना नहीं चाहते हैं। आप केवल अंदर के अशक्त चरित्र के लिए परीक्षण कर रहे हैं if(isspace(words[i])) ब्लॉक करें, लेकिन अगर चरित्र एक स्थान है तो यह"टी भी शून्य टर्मिनेटर हो सकता है। नतीजतन, आप इनपुट के अंत में पिछले पढ़ रहे हैं, और स्ट्रिंग के एकरहित भाग में रिक्त स्थान की गिनती कर रहे हैं।"

int countWords(char words[]){
int nSpaces = 0;

for (int i=0; i<256 && words[i] != ""; i++){
if(isspace(words[i])){
nSpaces++;
}
}
// The number of words = the number of spaces + 1
return nSpaces + 1;
}

जवाब के लिए 0 № 2

isspace नई पंक्तियों (n), टैब (t), v, f और r को गिनता है।

शायद आप केवल सफेद-रिक्त स्थान चाहते हैं? केवल "" और "t" के लिए जांचें।