1

最后,我找到了将小写转换为大写并确定字符串是字母还是数字代码的解决方案,如下所示:

#include <cctype>
#include <iostream>
using namespace std;
int main()
{
  char ch;
  cout<<"Enter a character: ";
  gets(ch);

  if ( isalpha ( ch ) ) {
    if ( isupper ( ch ) ) {
      ch = tolower ( ch );

      cout<<"The lower case equivalent is "<< ch <<endl;
    }
    else {
      ch = toupper ( ch );
      cout<<"The upper case equivalent is "<< ch <<endl;
    }
  }
  else
    cout<<"The character is not a letter"<<endl;
  cin.get();
} 

如何改进上面的代码以获取字符串而不是单个字符?循环多次打印相同的语句。谢谢

4

3 回答 3

2

Fis 使用输入运算符读入一个字符串:

std::string input;
std::cin >> input;

或者,您可以使用std::getline来获取多个单词。

然后您可以使用std::transform将字符串转换为大写或小写。

您还可以使用基于范围的 for 循环来迭代字符串中的字符。

于 2013-03-04T08:25:00.320 回答
2

更新:这是输出一个单词的更清洁的解决方案。

#include <cctype>
#include <iostream>
#include <algorithm>
using namespace std;

char switch_case (char ch) {
  if ( isalpha ( ch ) ) {
      if ( isupper ( ch ) ) {
        return tolower ( ch );
     }
     else {
       return toupper ( ch );
     }
   }
  return '-';
}

int main()
{
  string str;
  cout<<"Enter a word: ";
  cin >> str;

  transform(str.begin(), str.end(), str.begin(), switch_case);
  cout << str << "\n";
}

此示例中使用了std ::transform 。


只需阅读整个单词并使用std::string::iterator一次迭代一个字母:

#include <cctype>
#include <iostream>
using namespace std;

int main() 
{
  string str;
  cout<<"Enter a word: ";
  cin >> str;

  for ( string::iterator it = str.begin(); it != str.end(); ++it ) {
    char ch = *it;
    if ( isalpha ( ch ) ) {
      if ( isupper ( ch ) ) {
        ch = tolower ( ch );

        cout<<"The lower case equivalent is "<< ch <<endl;
     }
     else {
       ch = toupper ( ch );
       cout<<"The upper case equivalent is "<< ch <<endl;
     }
   }
   else
     cout<<"The character is not a letter"<<endl;
 }
 cin.get();
}
于 2013-03-04T08:27:43.377 回答
1

C++11:

#include <cctype>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    cout << "Enter data: ";
    cin >> s;

    for (auto &ch : s)
    {
        if (isalpha(ch))
        {
            if (isupper(ch))
            {
                ch = tolower(ch);
                cout << "The lower case equivalent is " << ch << endl;
            }
            else
            {
                ch = toupper(ch);
                cout << "The upper case equivalent is " << ch << endl;
            }
        }
        else
            cout << "The character is not a letter" << endl;
    };
    cin.get();
} 

或者

#include <cctype>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;
int main()
{
    string s;
    cout << "Enter a string: ";
    cin >> s;

    transform(s.begin(), s.end(), s.begin(), [](char ch)
    {
       return isupper(ch)? tolower(ch) : toupper(ch);
    });
} 

如果你有g++try :g++ test.cpp -o test -std=c++11来编译。

于 2013-03-04T08:28:26.097 回答