Page 1 of 1
UPPERCASE and lowercase
Posted: Tue Nov 21, 2023 9:08 am
by sazanof
I'm only a beginner in C++ programming
Perhaps the question is very stupid, but nevertheless, I can't find how to translate a string into upper or lower case.
toupper() - not work, throws an error
std::uppercase() - std undeclared
on github - no same issues
on this forum - no same questions
How I can use standart libraries to convert char array to uppercase?
Re: UPPERCASE and lowercase
Posted: Tue Nov 21, 2023 3:27 pm
by MicroController
Code: Select all
#include <string>
void makeUpper(std::string& str) {
for(auto& c : str) {
c = std::toupper(c);
}
}
Re: UPPERCASE and lowercase
Posted: Tue Nov 21, 2023 3:54 pm
by sazanof
Thak you!
I tired
and
with your code
Code: Select all
void makeUpper(std::string& str) {
for(auto& c : str) {
c = std::toupper(c);
}
}
, but if I use
, I got
Code: Select all
fatal error: string: No such file or directory
I use this code in a component with cMake:
Code: Select all
idf_component_register(SRCS "wifi.c"
PRIV_REQUIRES esp_wifi esp_event nvs
INCLUDE_DIRS ".")
I Try to add
into PRIV_REQUIRES section, but it triggers an error...
And if I use #include <string.h> then I got this
Code: Select all
error: expected ')' before '::' token
30 | void makeUpper(std::string& str) {
| ^~
| )
Also I turn on formatter and it changed code like this
Code: Select all
void makeUpper(std::string &str)
{
for (auto &c : str)
{
c = std::toupper(c);
}
}
with the same error.
I do not understand what I doin wrong.
Re: UPPERCASE and lowercase
Posted: Tue Nov 21, 2023 4:00 pm
by sazanof
Maybe because "string" is CPP, and my file is wifi.c?
Re: UPPERCASE and lowercase
Posted: Tue Nov 21, 2023 4:24 pm
by MicroController
Yes, if you want to use C++ (including std::string) the source file has to be named ".cpp".
Re: UPPERCASE and lowercase
Posted: Wed Nov 22, 2023 5:57 pm
by sazanof
So, I corrected code like this
Code: Select all
void to_upper(char *str, char *out_str)
{
for (int i = 0; i < strlen(str); i++)
{
out_str[i] = toupper(str[i]);
}
}
Code: Select all
char *text = "this is uppercase string!";
char out_text[strlen(text)];
to_upper(text, out_text);
ESP_LOGI("UPPER", "%s", out_text);
Code: Select all
I (559) UPPER: THIS IS UPPERCASE STRING!
Re: UPPERCASE and lowercase
Posted: Wed Nov 22, 2023 11:37 pm
by MicroController
Great
For better efficiency I suggest a modification, to avoid strlen(str) being evaluated over and over again.
Code: Select all
void to_upper(const char *str, char *out_str)
{
while(*str != 0) {
*out_str = toupper(*str);
++str;
++out_str;
}
*out_str = 0;
}
Re: UPPERCASE and lowercase
Posted: Sat Nov 25, 2023 7:01 pm
by sazanof
Got It! Done! Thanks a lot again!