Change String value to uppercase in a C++ header file?

♀尐吖头ヾ 提交于 2019-12-11 20:21:26

问题


I'm trying to convert a String to uppercase in my header file function. However, when I try to do this I get an error saying "Cannot convert from 'class String' to 'char'.

Here's my code -

#ifndef PATIENT_DEMO_CLASS
#define PATIENT_DEMO_CLASS

// system defined preprocessor statement for cin/cout operations
#include <iostream.h>
// header file from book
#include "tstring.h"
#include <algorithm>
#include <string>

class PatientDemographicInformation
{
    private:
    // patient's state
    String patientState;

    public:
    // constructor
    PatientDemographicInformation(String state);

    // returns the patient's state in all capital letters
    String getPatientState( );
};
// assign values to constructor
PatientDemographicInformation::PatientDemographicInformation(String state)
{
    patientState = state;
}

String PatientDemographicInformation::getPatientState( )
{
    int i=0;
// ------The line below this is where my error occurs--------
    char str[] = {patientState};
    char c;
    while (str[i])
    {
    c=str[i];
    putchar (toupper(c));
    i++;
    }
    return patientState;
}

This is just the function section of code from the header file. 'patientState' is defined in the constructor as a String. Let me know if I need to post more code. Please help in anyway you can.

Thanks - Josh


回答1:


There is no such type as String in C++. If you mean C++/CLI then I think the return type should be declared as String ^. If it is simply a typo and you mean class std::string then it would be simpler to write

for ( char c : patientState ) putchar (toupper(c));



回答2:


You don't need to convert your String to a char[]: just process each character on the fly. Since you don't spell out the exact type and String is sufficiently different from std::string that it may be something different (in particular, the uppercase first character) it is unclear which operation can be used to access the characters within, however. In no case will you able to initialize a char str[], however: as a variable, this is a statically sized array with the size derived from the initialization.

However, one thing you need to do is to make sure you only pass valid arguments to toupper(): this function consumes only positive values and the special value EOF. However, char may be signed, i.e., you shall use toupper() like so:

toupper(static_cast<unsigned char>(c))

where c is a char you obtained from somewhere.




回答3:


Look at Std::string::c_str this might be what you were looking for



来源:https://stackoverflow.com/questions/20182366/change-string-value-to-uppercase-in-a-c-header-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!