我需要找出我的程序的错误。当我输入 Hello World我时,它应该计算空格数,但我会继续 0 或 1 。以下是我的完整计划:
#include "windows.h"
#include <iostream>
#include <cctype>
using namespace std;
//Global declarations.
//Function prototypes.
void pause();
void numWords(string&);
int numWords(char []);
int main()
{
string userVal;
numWords(userVal);
char *conStr= new char[userVal.length()];
strcpy(conStr, userVal.c_str()); //String converted to a C-string.
int fin= numWords(conStr);
cout<< "The number of words in the sentence is "<< fin<< "."<< endl;
delete[] conStr;
conStr= 0;
pause();
return 0;
}
/***************************************FUNCTIONS**********************************************************************/
/*1st function to pause the program.*/
void pause()
{
cin.sync();
cin.ignore();
}
/*2nd function to ask the user for input. OP*/
void numWords(string &len)
{
cout << "Please enter a sentence and I will tell you how many words it has: " << endl;
cin >> len;
}
/*3rd function to count the number of total spaces in the sentence.*/
int numWords(char usStr[])
{
int wrdCount= 0,
chrCount= 0,
index= 0;
while(usStr[index]!= '\0')
{
if(isspace(usStr[index]))
{
if(chrCount)
{
wrdCount++;
chrCount= 0;
}
}
else
chrCount++;
index++;
}
if(chrCount)
wrdCount++;
return wrdCount;
}
任何人都可以解释为什么它不计算空格,或者我是否需要另一个循环机制才能使其工作?谢谢。
答案 0 :(得分:0)
CoryKramer的建议是正确的。 cin
将在第一个空格后停止。如果您想阅读整行,请使用getline
。我已对代码进行了更改以显示此内容,并重命名了用于从用户处获取句子的函数。此外,您不必转换为c样式的字符串,以使其工作,字符串工作正常。
//Function prototypes.
void pause();
void getSentence(string&);
int numWords(string&);
int main()
{
string userVal;
getSentence(userVal);
int fin = numWords(userVal);
cout << "The number of words in the sentence is " << fin << "." << endl;
pause();
return 0;
}
void getSentence(string &len)
{
cout << "Please enter a sentence and I will tell you how many words it has: " << endl;
getline(cin, len);
}
int numWords(string& usStr)
{
int wrdCount = 0,
chrCount = 0,
index = 0;
while(index < usStr.length())
{
...
}
if(chrCount)
wrdCount++;
return wrdCount;
}
您可能也想要#include <string>