Подтвердить что ты не робот

Как преобразовать строку C++ в верхний регистр

Мне нужно преобразовать строку в C++ в полный верхний регистр. Я искал какое-то время и нашел один способ сделать это:

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

using namespace std;

int main()
{
    string input;
    cin >> input;

    transform(input.begin(), input.end(), input.begin(), toupper);

    cout << input;
    return 0;
}

К сожалению, это не сработало, и я получил это сообщение об ошибке:

нет соответствующей функции для вызова to transform (std :: basic_string :: iterator, std :: basic_string :: iterator, std :: basic_string :: iterator,

Я пробовал другие методы, которые также не работали. Это было ближе всего к работе.

Так что я спрашиваю, что я делаю неправильно. Может быть, мой синтаксис плох или мне нужно что-то включить. Я не уверен.

Я получил большую часть своей информации здесь: http://www.cplusplus.com/forum/beginner/75634/ (последние два сообщения)

4b9b3361

Ответ 1

Вам нужно поставить двойную двоеточию перед toupper:

transform(input.begin(), input.end(), input.begin(), ::toupper);

Объяснение:

Есть два различных toupper функции:

  1. toupper в глобальном пространстве имен (доступ с помощью ::toupper), который исходит от C.

  2. toupper в пространстве имен std (доступ с помощью std::toupper), который имеет несколько перегрузок и поэтому не может просто ссылаться только на имя. Вы должны явно применить его к определенной сигнатуре функции для ссылки, но код для получения указателя функции выглядит уродливым: static_cast<int (*)(int)>(&std::toupper)

Поскольку вы using namespace std, при написании toupper, 2. скрывает 1. и поэтому выбирается в соответствии с правилами разрешения имен.

Ответ 3

Попробуйте эту небольшую программу, прямо из C++ ссылки

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

using namespace std;

int main()
{
    string s;
    cin >> s;
    std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
    cout << s;
    return 0;

}

Демо-версия

Ответ 4

Вы можете сделать:

string name = "john doe"; //or just get string from user...
for(int i = 0; i < name.size(); i++) {
    name.at(i) = toupper(name.at(i));
}

Ответ 5

#include <iostream>

using namespace std;

//function for converting string to upper
string stringToUpper(string oString){
   for(int i = 0; i < oString.length(); i++){
       oString[i] = toupper(oString[i]);
    }
    return oString;
}

int main()
{
    //use the function to convert string. No additional variables needed.
    cout << stringToUpper("Hello world!") << endl;
    return 0;
}

Ответ 6

Вы также можете использовать функцию из кода ниже, чтобы преобразовать ее в верхний регистр.

#include<iostream>
#include<cstring>

using namespace std;

//Function for Converting Lower-Case to Upper-Case
void fnConvertUpper(char str[], char* des)
{
    int i;
    char c[1 + 1];
    memset(des, 0, sizeof(des)); //memset the variable before using it.
    for (i = 0; i <= strlen(str); i++) {
        memset(c, 0, sizeof(c));
        if (str[i] >= 97 && str[i] <= 122) {
            c[0] = str[i] - 32;    // here we are storing the converted value into 'c' variable, hence we are memseting it inside the for loop, so before storing a new value we are clearing the old value in 'c'.
        } else {
            c[0] = str[i];
        }
        strncat(des, &c[0], 1);
    }
}

int main()
{
    char str[20];  //Source Variable
    char des[20];  //Destination Variable

    //memset the variables before using it so as to clear any values which it contains,it can also be a junk value.
    memset(str, 0, sizeof(str));  
    memset(des, 0, sizeof(des));

    cout << "Enter the String (Enter First Name) : ";
    cin >> str; //getting the value from the user and storing it into Source variable.

    fnConvertUpper(str, des); //Now passing the source variable(which has Lower-Case value) along with destination variable, once the function is successfully executed the destination variable will contain the value in Upper-Case

    cout << "\nThe String in Uppercase = " << des << "\n"; //now print the destination variable to check the Converted Value.
}