我是一名学习C++的初学者。目前我正在研究函数、C 字符串和引用传递。
下面的程序旨在从输入中获取字符串,用连字符替换所有空格,用问号替换所有感叹号。
如果下面的函数 StrSpaceToHyphen() 的返回类型为 void,那么函数参数是否需要通过引用传递才能修改 main() 中的 userStr?
下面复制的程序按预期工作。我的问题旨在进一步加深我对修改 C 字符串的理解,因为我期望它的行为有所不同。
#include <iostream>
#include <cstring>
using namespace std;
// Function replaces spaces with hyphens
void StrSpaceToHyphen(char modString[]) {
int i; // Loop index
for (i = 0; i < strlen(modString); ++i) {
if (modString[i] == ' ') {
modString[i] = '-';
}
if (modString[i] == '!') {
modString[i] = '?';
}
}
}
int main() {
const int INPUT_STR_SIZE = 50; // Input C string size
char userStr[INPUT_STR_SIZE]; // Input C string from user
// Prompt user for input
cout << "Enter string with spaces: " << endl;
cin.getline(userStr, INPUT_STR_SIZE);
// Call function to modify user defined C string
StrSpaceToHyphen(userStr);
cout << "String with hyphens: " << userStr << endl;
return 0;
}
type here
我通过引用传递函数参数,但程序无法编译。
最佳答案
这个参数的声明
void StrSpaceToHyphen(char & modString[]) {
声明一个引用数组。您不能声明引用数组。
至于您的初始声明
void StrSpaceToHyphen(char modString[]) {
然后编译器将具有数组类型的参数调整为指向数组元素类型的指针,例如
void StrSpaceToHyphen(char *modString) {
由于数组的地址在函数内没有更改,因此将参数声明为对指针的引用是没有意义的
void StrSpaceToHyphen(char * &modString) {
有了指向数组第一个元素的指针和指针算术,您可以更改原始数组的任何元素。
注意变量i和strlen
的调用是多余的。
您可以通过以下方式定义函数
char * StrSpaceToHyphen( char modString[] )
{
for ( char *p = modString; *p; ++p )
{
if ( *p == ' ' )
{
*p = '-';
}
else if ( *p == '!' )
{
*p = '?';
}
}
return modString;
}
关于C++字符串修改,不通过引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74337633/