C++ 如何循环字符串并转换为小写?
我知道很久以前还有一些其他的问题,但是我看了一遍,还是没弄明白。我试图以字符串的形式获取用户输入,然后循环使用该字符串,将所有大写字母转换为小写字母,以便以小写字母显示所有内容。 我哪里做错了C++ 如何循环字符串并转换为小写?,c++,string,C++,String,我知道很久以前还有一些其他的问题,但是我看了一遍,还是没弄明白。我试图以字符串的形式获取用户输入,然后循环使用该字符串,将所有大写字母转换为小写字母,以便以小写字母显示所有内容。 我哪里做错了 int main() { cout << "Enter Text: "; string Text; getline(cin, Text); for(int i=0; i<Text.length(); i++) { if(islowe
int main()
{
cout << "Enter Text: ";
string Text;
getline(cin, Text);
for(int i=0; i<Text.length(); i++)
{
if(islower(Text[i]) == false)
{
tolower(Text[i]);
i++;
}
Text[i] = Text[i];
}
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
我对C++很陌生,如果我说我有很多想法,即使我出了问题,我也会撒谎。第11行,for循环表示它试图比较两个不同的符号,但我不知道这意味着什么,或者这是否是我问题的根源。第15行的tolower表示“忽略用pure属性声明的函数的返回值”,但我仍然不知道这意味着什么。
请提供帮助。我建议查看ascii表格,查看大写和小写字符的代码。 因为所有字符本质上都是整数,所以只需使用ascii值即可获得所需的值。以下几点: tolower返回小写字符(如果存在)'A'变为 “a”、“a”不变,“9”不变,等等。 行Text[i]=文本[i];不做任何事情,您需要文本[i] =tolowerText[i]; 不需要检查每个字符是否为小写,tolower 我会帮你处理的 简化:
我建议使用std库算法函数转换来简化代码,并使代码更易于您和其他人阅读
#include <iostream> //for cout and getline
#include <algorithm> //for transform
int main()
{
cout << "Enter Text: ";
string Text;
getline(cin, Text);
//This will iterate over each character [Text.begin()-Text.end()] and then
//replace it by a call to tolower with itself as a parameter
transform(Text.begin(), Text.end(), Text.begin(), ::tolower);
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
这不是将tolower用作std::transform谓词的正确方法。有关正确方法的说明和示例,请参阅。这也应适用于亚洲答案。
#include <iostream>
using namespace std;
int main() {
cout << "Enter Text: ";
string Text;
getline(cin, Text);
for (int i = 0; i < Text.length(); i++)
Text[i] = tolower(Text[i]);
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
#include <iostream> //for cout and getline
#include <algorithm> //for transform
int main()
{
cout << "Enter Text: ";
string Text;
getline(cin, Text);
//This will iterate over each character [Text.begin()-Text.end()] and then
//replace it by a call to tolower with itself as a parameter
transform(Text.begin(), Text.end(), Text.begin(), ::tolower);
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
transform(Text.begin(), Text.end(), Text.begin(),
[](unsigned char c){ return std::tolower(c); });