简体   繁体   中英

c++ formating error with cstrings when using tolower

Hi so I am trying to take a cstring and make it lowercase, but when I am printing the cstring at the end I am getting a weird format box where some of the letters should be. Do anyone have any ideas?

#include <string>
#include <iostream>
#include <string.h>

using namespace std;

int main () 
{ 
    int i=0; 
    char* str="TEST"; 
    char c; 
    char* cstr = new char[strlen(str) + 1];
    while (str[i]) 
    { 
        c = str[i]; 
        c = tolower(c);
        strcat(cstr, &c); 
        i++; 
    } 

    cout << cstr << endl; 
    return 0; 
}

The problem is that you are calling strcat incorrectly. The second parameter is not a null-terminated string.

You really don't need to call strcat at all. Just write directly to the output string:

Try:

  while (str[i])
  {
    c = str[i];
    c = tolower(c);
    cstr[i] = c;
        i++;
  }
  cstr[i] = 0;

or, equivalently:

while(str[i])
{
  cstr[i] = tolower(str[i]);
  i++;
}
cstr[i] = 0;

strcat expects a null-terminated char* , so by giving the address of a local char you are invoking undefined behavior .

Additionally, new char[std::strlen(str) + 1] does not initialize the array to 0 s, meaning cstr won't be properly null-terminated either; adding () to the new[] causes the array to be value-initialized.

Try this instead:

#include <cstddef>
#include <cctype>
#include <cstring>
#include <ostream>
#include <iostream>

int main()
{
    char const* str = "TEST";
    char c[2] = { };
    char* cstr = new char[std::strlen(str) + 1]();
    std::size_t i = 0;
    while (str[i])
    {
        c[0] = static_cast<char>(std::tolower(str[i++]));
        std::strcat(cstr, c);
    }
    std::cout << cstr << std::endl;
    delete [] cstr;
}

The second argument of strcat is supposed to be a null terminated string, not the address of a single character. strcat isn't appropriate for this use.

int main ()
{
    const char* str="TEST";
    char* cstr = new char[strlen(str) + 1];
    cstr[strlen(str)] = 0;
    for (int i = 0; str[i]; ++i) {
        cstr[i] = tolower(str[i]);
    }
    cout << cstr << endl;
}
#include <cstddef>
#include <cctype>
#include <cstring>
#include <ostream>
#include <iostream>

#include <string>

int main()
{
    std::string str = "TEST";
    std::string cstr;

    for (std::string::const_iterator it = str.begin(); it!= str.end(); ++it)
        cstr.push_back(tolower(*it));

    std::cout << cstr << std::endl;
}

Or even shorter:

#include <algorithm>
#include <iterator>

...

    std::transform(str.begin(), str.end(), std::back_inserter(cstr), tolower);

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