简体   繁体   中英

Issue using toupper function in c++

I have an assignment for my c++ class where I must use cstring for strings.

The assignment is supposed to be a program that accepts input from the user for the first and the last name. Then the program has to convert the first letter of the first name to a Uppercase. As well convert the last letter of the last name to Uppercase. I was able to find a way to convert the first letter of the first name to uppercase; however couldn't replace the lowercase letter with the upper case letter. In addition, couldn't figure out how to capitalize the last letter of the last name.

This is the part of the code related to the problem.

#include <iostream>
#include <cstring>
#include <cctype>

using std::cout;
using std::cin;

int main()
{
    //Variable Declaration
    char firstName[50];
    char secondName[50];
    char second[50];
    char firstLetter;
    int result;
    int charLength;

//Program Header
    cout << "\t\t>>>>>>>> Welcome to The Bog Office of Names <<<<<<<<";

        cout << "\nEnter first name: ";
        cin >> firstName;
        cout << "\nEnter second name: ";
        cin >> secondName;

            firstLetter= toupper(secondName[0]);
            firstLetter = toupper(firstLetter);

            cout << "\nFormatted name: " << secondName << " " << firstName;


    return 0;
}

You are just storing uppercase letter to firstLetter which is not helping:

int len=strlen(secondName);
firstName[0] = toupper(firstName[0]);

For accessing last letter use len-1 as len='\\0'

secondName[len-1] = toupper(secondName[len-1]);  //notice len-1

try this:

firstName[0] = toupper(firstName[0]);
secondName[0] = toupper(secondName[0]);
secondName[strlen(secondName)-1] = toupper(secondName[strlen(secondName)-1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM