[英]Transform a void function into char* C++
Some guy presented me with a beautiful code in my other question. 在另一个问题中,有人向我提供了漂亮的代码。 Here it is:
这里是:
#include <iostream>
#include <cstring>
using namespace std;
void encode(char* source, char const* alpha)
{
int i, j;
int len = strlen(source);
for (i = 0; i < len; i++)
{
if (source[i] >= 'a' && source[i] <= 'z')
{
j = source[i] - 'a';
source[i] = alpha[j];
}
}
}
int main(void)
{
char source[1001];
char alpha[27];
cin.getline(source, 1001);
cin.getline(alpha, 27);
encode(source, alpha);
cout << source;
return 0;
}
What should I do to transform this void
function into a char*
one (it should become char* encode(char* source, char const* alpha)
)? 我应该怎么做才能将此
void
函数转换为char*
一个(它应该变成char* encode(char* source, char const* alpha)
)? Apparently as it won't be a 'void' it should return a value but what value? 显然,因为它不是一个“空”,它应该返回一个值,但是什么值呢? Those pointers confuse me immensely.
这些指针使我非常困惑。
#include <iostream>
#include <cstring>
using namespace std;
char* encode(char* source, char const* alpha)
{
int i, j;
int len = strlen(source);
for (i = 0; i < len; i++)
{
if (source[i] >= 'a' && source[i] <= 'z')
{
j = source[i] - 'a';
source[i] = alpha[j];
}
}
return source;
}
int main()
{
char source[1001];
char alpha[27];
cin.getline(source, 1001);
cin.getline(alpha, 27);
cout << encode(source, alpha);
return 0;
}
Do something like that. 做这样的事情。 And if you want to change a char array of main, your void function would work.
而且,如果您要更改main的char数组,则可以使用void函数。 :)
:)
char* encode(char* source, char const* alpha)
{
int i, j;
int len = strlen(source);
for (i = 0; i < len; i++)
{
if (source[i] >= 'a' && source[i] <= 'z')
{
j = source[i] - 'a';
source[i] = alpha[j];
}
}
return source;
}
Though it doesn't look like your doing anything with that return value. 虽然看起来不像您使用该返回值执行任何操作。
(Were you supposed to return a copy of the char
array, or is modifying in-place it okay?) (您应该返回
char
数组的副本,还是就地对其进行修改?)
Returning char *
really only makes sense if you're trying to alert the calling function an error has occurred: 仅当您试图警告调用函数发生错误时,才返回
char *
才有意义:
char *encode(char *source, char const *alpha)
{
int i, j;
int len = strlen(source);
/* Check For Argument Errors */
if((source == NULL) || (alpha == NULL))
return NULL;
for (i = 0; i < len; i++)
{
if (source[i] >= 'a' && source[i] <= 'z')
{
j = source[i] - 'a';
source[i] = alpha[j];
}
}
return source;
}
The calling function can check for errors like this: 调用函数可以检查如下错误:
if(encode(source, alpha) == NULL)
{
printf("Encoding error!\n");
return -1;
}
else
{
cout << source;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.