使用"if"打印大写字母

Printing uppercase letters using 'if'

本文关键字:大写字母 打印 if 使用      更新时间:2023-10-16

我做错了什么?我需要这个,使用'if'打印所有大写字母,但是有些东西是错误的,因为它打印一个字母不止一次!感谢任何帮助:)

//Uppercase letters using if;
#include<iostream>
using namespace std;
int main()
{
    char character='A';
label1:
if(character>='A')
    if(character>='Z')
        goto label2;
    else
    {
        cout<<character<<endl<<character++<<endl;
        goto label1;
    }
label2:
    cout<<"End"<<endl;
    return 0;
}

character变量增加两次。我发布这个答案只是为了告诉你什么是技术上的错误,但有一个更大的概念上的错误,这是使用goto。我建议你读一些c++的入门书籍。

//Uppercase letters using if;
#include<iostream>
using namespace std;
int main()
{
    char character='A';
label1:
if(character>='A')
    if(character>'Z'))
        goto label2;
    else
    {
        cout<<character<<endl;
        character++;
        goto label1;
    }
label2:
    cout<<"End"<<endl;
    return 0;
}

每个字母多次打印的原因如下:

    cout<<character<<endl<<character++<<endl;
          ^^^^^^^^^        ^^^^^^^^^

以上每一个都将导致character被写入cout

有点晚了,但是:

#include "stdafx.h"
#include<iostream>
#include <string>
using namespace std;
int main()
{
    string s("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    if (1) goto label1;
    cout << "End" << endl;
    return 0;
label1:
    cout << s << endl;
    return 0;
}

你的代码漏掉了两点-

  1. 未打印Z
  2. 打印字符两次cout<<character<<endl<<character++<<endl;

改变:if(character>='Z') to if(character>'Z')

EDITED character++(这是打字错误)cout<<character<<endl<<character++<<endl; cout<<character++<<endl;