为什么我总是在我的代码中得到“false”
问题描述:
我写了代码来检查输入,我设置的HavePunct
标志总是false
。但是,当我输入hello,world!!
它将错误的结果返回给我。请让我知道如果您看到我的代码有任何问题:为什么我总是在我的代码中得到“false”
#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();
+0
感谢您的帮助,我以前没有意识到这个问题。 –
+0
@ y.ferocious,不客气。 –
答
我不能肯定,但它似乎是因为你的迭代器的上限由变量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;
}
您是否尝试过步进以为他调试器了吗? –
看看你在哪里设置'sLen'。字符串是否已填充? – NathanOliver