为什么我总是在代码中得到"false"
why i always get "false" in my code
我编写了代码来检查输入,我始终将HavePunct
标志设置为false
。但是,当我输入hello,world!!
时,它会向我返回错误的结果。如果您发现我的代码有任何问题,请告诉我:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s,result_s;
char ch;
bool HavePunct = false;
int sLen = s.size();
cout << "Enter a string:" << endl;
getline(cin, s);
//检测字符串是否有符号
for (string::size_type i = 0;i != sLen; ++i) {
ch = s[i];
if (ispunct(ch)) {
HavePunct = true;
}
else
result_s += ch;
}
if (HavePunct) {
cout << "Result:" << result_s;
}
else {
cerr << "No punction in enter string!" << endl;
system("pause");
return -1;
}
system("pause");
return 0;
}
在输入任何输入之前,您正在计算行的长度。因此,sLen
始终为零。移动该行,使其位于读取输入的行之后。
cout << "Enter a string:" << endl;
getline(cin, s);
int sLen = s.size();
我不确定,但是看起来是因为您的迭代器的上限是由变量sLen
决定的,您在收到字符串之前将其指定为s.size()
,因此有效地使您的上限为 0 并导致您的 for 循环永远不会执行。
试试这个,让我知道:
getline(cin, s);
int sLen = s.size();
for (string::size_type i = 0;i != sLen; ++i) {
ch = s[i];
if (ispunct(ch)) {
HavePunct = true;
}
else
result_s += ch;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 伪造事实↔false
- 编译包含字符串的代码时遇到问题
- QueryWorkingSet总是返回false
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 为什么我总是在代码中得到"false"
- 使用代码调整删除"comparison is always false"警告
- 为什么enumProcessModules返回false值和299代码错误
- 如果模板的错误代码在If(false)中,我必须专门化模板吗
- 块"If"中的代码不会运行,即使使其为 false 的条件在块内
- 如何编写一个c++代码,使函数在初始参数为大写时返回true,如果不是,则返回false
- 添加' noexcept(false) '是否对代码有任何好处?
- 如何使用常量数组从代码中的函数返回true或false