将大写字母(从cin读取)更改为小写?

时间:2014-03-05 05:58:11

标签: c++ string

  

我想将输入的首都cin更改为小写,例如,如果cin>>一   one = R它应该是r所以它会自动转换

    #include <cctype>
#include <iostream>

using namespace std;
int main ()
{
    string one;
    string two;
cout << "\nPlayer One, please enter your move: ('p'  for Paper, 'r' for Rock, '$
cin >> one;

cout <<"\nPlayer Two, please enter your move: ('P' for Paper, 'R' for Rock, 'S'$
cin >> two;

5 个答案:

答案 0 :(得分:1)

您可以使用transform:

编写代码
string one;
string two;
cout << "\nPlayer One, please enter your move: ('p'  for Paper, 'r' for Rock, '" << std::endl;
cin >> one;

std::transform(one.begin(), one.end(), one.begin(), ::tolower);
cout <<"\nPlayer Two, please enter your move: ('P' for Paper, 'R' for Rock, 'S'" << std::endl;
cin >> two;
std::transform(two.begin(), two.end(), two.begin(), ::tolower);
std::cout << "one=" << one << " ; two=" << two << std::endl;

输出可能如下(对于R,P):

Player One, please enter your move: ('p'  for Paper, 'r' for Rock, '
R

Player Two, please enter your move: ('P' for Paper, 'R' for Rock, 'S'
P
one=r ; two=p

答案 1 :(得分:0)

尝试:

#include <ctype>

tolower(char)

对于字符串输入,您必须逐个字符地转换:

char str[]="ONE TWO\n";
char c;
int i=0;
while (str[i])
{
  c=str[i];
  str[i] = (char) tolower(c);  //I think it return an int, which you need to typecast to a char
  i++;
}

答案 2 :(得分:0)

转换是正确的方法,我认为,你只需要包含算法库

#include <ctype>
#include <algorithm>
#include <string>

std::transform(one.begin(), one.end(), one.begin(), ::tolower); 
std::transform(two.begin(), two.end(), two.begin(), ::tolower);

答案 3 :(得分:0)

在头文件“ctype.h”中 有支持案例格式化的功能

如:tolower(var)将文本格式化为小写,           toupper(var)将文本格式化为大写

答案 4 :(得分:0)

您应该将字符存储在变量中并更改变量

#include <cctype>
#include <iostream>

using namespace std;
int main ()
{
    char one{};
    char two{};
cout << "\nPlayer One, please enter your move: ('p'  for Paper, 'r' for Rock, '$
cin >> one;
one = tolower(one);

cout <<"\nPlayer Two, please enter your move: ('P' for Paper, 'R' for Rock, 'S'$
cin >> two;
one = tolower(two);