无法使ispunct或isspace工作,但isupper工作正常.你能帮我吗
Cannot get ispunct or isspace to work, but isupper works fine. Can you help me?
此代码仅输出大写字母的数目。它总是将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,而且效果很好。谢谢你提供的信息。现在我知道未来的
您正在使用的函数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
错误地使用了它;参数必须在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
返回零,但不能假定它总是。如果是空格或制表位,则返回1
http://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)。
我希望这能帮助
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 无法使ispunct或isspace工作,但isupper工作正常.你能帮我吗