无法使ispunct或isspace工作,但isupper工作正常.你能帮我吗

Cannot get ispunct or isspace to work, but isupper works fine. Can you help me?

本文关键字:工作 isupper ispunct isspace      更新时间:2023-10-16

此代码仅输出大写字母的数目。它总是将numMarks和numSpaces输出为0。我也试过句子.c_str(),得到了同样的结果。我不明白发生了什么。

cout << "Please enter a sentence using grammatically correct formatting." << endl;
string sentence = GetLine();
int numSpaces = 0;
int numMarks = 0;
int numCaps = 0;
char words[sentence.length()];
for(int i = 0; i < sentence.length(); ++i)
{
words[i] = sentence[i];
if(isspace(words[i]) == true)
{
numSpaces++;
}
else if(ispunct(words[i]) == true)
{
numMarks++;
}
else if(isupper(words[i]) == true)
{
numCaps++;
}
}
cout << "nNumber of spaces: " << numSpaces;
cout << "nNumber of punctuation marks: " << numMarks;
cout << "nNumber of capital letters: " << numCaps;

编辑:修复了问题。我的编译器很奇怪。我所要做的就是删除==true,而且效果很好。谢谢你提供的信息。现在我知道未来的

您正在使用的函数isspaceispunctisupper的返回类型为int。如果不匹配则返回0,如果匹配则返回非零。它们不一定返回1,因此即使检查成功,测试== true也可能失败。

将您的代码更改为:

if ( isspace(words[i]) )   // no == true

它应该开始正常工作(只要你不键入任何扩展字符-见下文)。


进一步信息:C++中有两个不同的isupper函数(其他两个函数也是如此)。它们是:

#include <cctype>
int isupper(int ch)

#include <locale>
template< class charT >
bool isupper( charT ch, const locale& loc );

您当前正在使用第一个函数,它是来自C的遗留函数。但是,您通过传递char错误地使用了它;参数必须在CCD_ 10的范围内。相关问题。

因此,要正确修复代码,请选择以下两个选项之一(包括右侧标题):

if ( isupper( static_cast<unsigned char>(words[i]) ) )

if ( isupper( words[i], locale() ) )

其他事项:char words[sentence.length()];在标准C++中是非法的;数组维度必须在编译时已知。您的编译器正在实现一个扩展。

然而,这是多余的,您可以只写sentence[i],而根本不使用words

请将您的代码更改为

char c;
...
c = sentence[i];
if(isspace(c))
{
++numSpaces;
}
...

如果不是空格或制表符,则isspace返回零,但不能假定它总是。如果是空格或制表位,则返回1http://www.cplusplus.com/reference/cctype/isspace/,它说,">如果c确实是空白字符,则为不同于零的值(即true)。否则为零(即false)。">

但是,如果您使用true测试它,true将转换为1,并且测试失败,因为例如,在我的机器上,它返回一个空间的8

需要考虑两件事。

首先,我会使用"else-if(ispunct(words[I])!=0)",而不是将函数的返回值与true进行比较。这是因为函数返回一个整数。返回的整数的值可能与等于平台或编译器中定义的任何true的情况不匹配。

我的第二个建议是检查一下你的地区。在unix中,您可以使用"locale"命令。在windows中,你可以询问谷歌如何检查你的区域设置,例如windows7。

https://www.java.com/en/download/help/locale.xml

如果您的区域设置是"宽字符"区域设置,则可能需要使用iswpunct(wint_t-wc)而不是ispunct(int c)。

我希望这能帮助