使用C ++中的ASCII代码将输入从小写转换为大写

时间:2018-10-18 15:58:20

标签: c++ arrays string ascii

这是我在这里的第一个问题,所以我已尽力使这成为一个好问题。

我正在创建一个程序,该程序实质上需要用户输入并将所有字符都转换为大写。我正在使用for循环使用相应的ASCII代码扫描小写字符。

我可以使用分配了代码内字符串char text[] = "Text"的字符数组来做到这一点。

我希望能够接受用户输入并在字符数组中使用它。我尝试使用getline(cin,myString)并为此分配字符数组,但是它说必须使用括号括起来的初始化程序来初始化数组。

我使字符数组保持未初始化状态,因为初始化数组时sizeof(text)没有给出正确的大小。我正在阅读有关使用指针的内容,但是在这个话题上我还是有点新鲜。下面是我写的代码:

int main() {
    // User input as a string
    char textConvert[] = "This text will be converted to uppercase.";
    cout << textConvert << endl;
    int endChar = sizeof(textConvert); //Only gives correct size when array is uninitialized
    for (int i = 0; i < endChar; i++) {
        if (textConvert[i] >= 97 && textConvert[i] <= 122) {
            textConvert[i] = textConvert[i] - 32;
        }
    }
    cout << textConvert;
    return 0;
}

2 个答案:

答案 0 :(得分:1)

问题:

  

我尝试使用getline(cin,myString)并为其分配字符数组,但是它说必须使用大括号括起的初始化程序来初始化数组

编译器在这里计算出所需数组的大小。

    char textConvert[] = "This text will be converted to uppercase.";

如果要用户输入,则需要分配一个数组并指定大小。

    char textConvert[50];

现在您可以读取一行并将其复制到数组中:

    std::string myString;
    std::getline(std::cin , myString);
    // Should check that the string is not more than 50 characters.
    std::copy(std::begin(myString), std::end(myString), textConvert);

但实际上根本不需要这样做。只需使用std::string并遍历字符串即可。最好避免使用C结构,例如数组,并使用C ++结构来阻止您出错。

字符串大小

这不是一个好主意。

    int endChar = sizeof(textConvert);

这将测量数组的大小(而不是字符串的大小)。还有一个问题,数组很容易衰减为指针。发生这种情况时,sizeof()将为您提供指针的大小(可能是4或8),而不是数组的大小。

要获取字符串的大小,请使用std::strlen()include <cstring>)。

但是实际上,您应该使用std::string C ++版本的字符串,它可以自己进行内存管理并根据需要调整大小。

魔术数字

不想使用幻数:

        if (textConvert[i] >= 97 && textConvert[i] <= 122) {
            textConvert[i] = textConvert[i] - 32;
        }

这些魔术数字使代码难以阅读。您可以改用字符常量。

        if (textConvert[i] >= 'a' && textConvert[i] <= 'z') {
            textConvert[i] = textConvert[i] - ('a' - 'A');
        }

首选标准库

但是不建议手动执行此操作。您应该使用标准的库例程。

std::islower() .  // Check if a character is lower case.
std::toupper() .  // Convert a lowercase character to upper.

// include <cctype>

C ++示例

尝试一下:

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

int main()
{
    std::string   myString;
    while(std::getline(std::cin, myString)) {
        std::cout << "User Input: " << myString << "\n";
        for(auto& c: myString) {
            c = std::toupper(c);
        }
        std::cout << "Upper Case: " << myString << "\n";
    }
}

答案 1 :(得分:0)

由于您正在处理ASCII,因此只能使用std::toupper

不需要编写自定义代码,标准库已为您提供。

相关问题