[英]I need help in c++ change cases
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence ="";
cin >> sentence; //aab
int i;
for (i=0;i=sentence.length();i++){
if (i<=65 && i>=90) {
sentence = sentence[i] + 32;
}
else if (i<=97 && i>=122){ //i=0,
sentence = sentence [i]-32;
}
}
cout << sentence;
return 0;
}
When I enter this code for changing cases of letters it keeps asking me to enter more although I have only one cin in the code why does that happen?当我输入此代码以更改字母大小写时,它不断要求我输入更多内容,尽管代码中只有一个 cin 为什么会发生这种情况?
Problem one is inadvertent assignment.问题一是疏忽分配。 Look at your loop condition:看看你的循环条件:
for (i=0;i=sentence.length();i++)
That assigns i
rather than comparing it, resulting in an infinite loop.这会分配i
而不是比较它,从而导致无限循环。 Use <
instead of =
:使用<
代替=
:
for (i=0; i < sentence.length(); i++)
Problem two is you're comparing the position in the string to the character ranges rather than the character itself, and the comparison is backwards and can never be true:问题二是您将字符串中的位置与字符范围而不是字符本身进行比较,并且比较是向后的并且永远不会为真:
if (i<=65 && i>=90)
Should be:应该:
if (sentence[i] >= 65 && sentence[i] <= 90)
Same for the lower case range.小写范围相同。
Finally, you don't want to change the whole sentence to one character, just that character:最后,您不想将整个句子更改为一个字符,仅更改该字符:
sentence = sentence[i] + 32;
Should be:应该:
sentence[i] = sentence[i] + 32;
Again, same for the lower case range.同样,小写范围也是如此。
With these changes, it seems to work, at least for single words.通过这些更改,它似乎有效,至少对于单个单词。 If you want to do entire sentences, I'd recommend using std::getline(std::cin, sentence);
如果你想做整个句子,我建议使用std::getline(std::cin, sentence);
rather than cin >> sentence;
而不是cin >> sentence;
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.