为什么我总是在代码中得到"false"

why i always get "false" in my code

本文关键字:false 代码 为什么      更新时间:2023-10-16

我编写了代码来检查输入,我始终将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;
}