【问题标题】:Cannot get ispunct or isspace to work, but isupper works fine. Can you help me?无法让 ispunct 或 isspace 工作,但 isupper 工作正常。你能帮助我吗?
【发布时间】:2015-07-08 02:38:21
【问题描述】:

此代码仅输出大写字母的数量。它总是将 numMarks 和 numSpaces 输出为 0。我也尝试过 sentence.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 并且效果很好。不过感谢您提供的信息。现在我知道未来了

【问题讨论】:

  • 请标记您正在使用的编程语言

标签: c++ char boolean


【解决方案1】:

您正在使用的函数isspace、ispunct、isupper 具有返回类型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 错误地使用它;参数必须在unsigned char 的范围内。 Related question.

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

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

或

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

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

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

【讨论】:

    【解决方案2】:

    请将您的代码更改为

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

    isspace 如果不是空格或制表符,则返回零,但你不能假设它总是返回1,如果它是空格或制表符。从http://www.cplusplus.com/reference/cctype/isspace/ 开始,它说:“如果 c 确实是空白字符,则该值不同于零(即 true)。否则为零(即 false)。”

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

    【讨论】:

    • 呃。避免 cplusplus.com,它写得不好。 C++ 中的true 等于一。但是,int 结果确实只有零或非零,这就是cppreference 所说的。
    【解决方案3】:

    需要考虑两件事。

    首先我会使用“ else if(ispunct(words[i]) !=0 )”,而不是比较函数的返回值和true。这是因为函数返回一个整数。返回的整数值可能与您的平台或编译器中定义的任何真值都不匹配。

    我的第二个建议是检查您的语言环境。在 unix 中,您可以使用“locale”命令。在 Windows 中,您可以询问 google 如何检查您的语言环境,例如 Windows 7。

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

    如果您的语言环境是“宽字符”语言环境,您可能需要使用 iswpunct (wint_t wc) 而不是 ispunct(int c)。

    希望对你有帮助

    【讨论】:

    • 要使用iswpunct,首先需要将字符串转换为wstring
    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    相关资源
    最近更新 更多