我想在不使用STL的情况下在c ++中为tolower()编写函数。当我给出像“Hello”这样的小输入时,我的代码输出正确,但是当我输入带有大量段落的输入时,我就会收到错误。任何人都可以帮助修复并帮助理解我为什么会收到错误?
我的代码:
#include <iostream>
using namespace std;
int main()
{
std::string str[] = ""Mymommaalwayssaid,\"Lifewaslikeaboxofchocolates.Youneverknowwhatyou'regonnaget.""
int n ,i;
string UP[str.size()];
for(int i=0;i<=str.size();i++)
{
if(int(str[i])<=90 && int(str[i])>=65)
{ n = int(str[i]);
n= n+32;
UP[i]=char(n);
}
else
UP[i] = str[i];
}
cout<<UP<<endl;
return 0;
}
那么,这个问题有几个令人困惑的问题。首先,问题要求tolower()的示例,但代码似乎想要创建一个名为UP的字符串。
我继续创建了一个string_to_lower()函数。我不想使用与tolower(char * str)相同的名称,尽管这样可行。
#include <iostream>
#include <string>
std::string string_to_lower(std::string str) {
const uint diff = 'a' - 'A'; // create a constant from the ascii chars
std::string lower; // return string. Could be done with an inline reference.
lower.reserve(str.length());
for (int i = 0; i < str.size(); i++) { // Use a ternary to set each char
lower += (str[i] >= 'A' && str[i] <= 'Z') ? str[i] + diff : str[i];
}
return lower;
}
int main()
{
std::string str = {"My momma always said, \"Life "
"is like a box of chocolates."
"You never know what you're gonna get.\""};
std::string lower = string_to_lower(str);
std::cout << lower << std::endl;
return 0;
}
接近代码并更正错误的定义是:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Mymommaalwayssaid,\"Lifewaslikeaboxofchocolates.Youneverknowwhatyou'regonnaget.";
string lower = str;
for (size_t i = 0; i < lower.length(); ++i) // can also use an iterator
{
char c = lower[i];
if ((c >= 'A') && (c <= 'Z'))
lower[i] += ('a' - 'A');
}
cout << lower <<endl;
return 0;
}
编译和执行
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra t.cc
pi@raspberrypi:/tmp $ ./a.out
mymommaalwayssaid,"lifewaslikeaboxofchocolates.youneverknowwhatyou'regonnaget.
但我不明白,因为你说不使用STL而你使用std :: string。
没有std :: string(iostream可以被stdio.h替换)
#include <iostream>
using namespace std;
int main()
{
const char str[] = "Mymommaalwayssaid,\"Lifewaslikeaboxofchocolates.Youneverknowwhatyou'regonnaget.";
char lower[sizeof(str) + 1]; // if str content unknown so sizeof unknown => strlen and new/malloc etc
for (size_t i = 0 ; i != sizeof(str); ++i)
{
char c = str[i];
if ((c >= 'A') && (c <= 'Z'))
c += ('a' - 'A');
lower[i] = c;
}
lower[sizeof(str)] = 0;
cout << lower <<endl;
return 0;
}
编译和执行
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra t.cc
pi@raspberrypi:/tmp $ ./a.out
mymommaalwayssaid,"lifewaslikeaboxofchocolates.youneverknowwhatyou'regonnaget.