C++字符串修改,不通过引用传递?

标签 c++ arrays pass-by-reference c-strings function-declaration

我是一名学习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/

相关文章:

c++ - 使用 Qt C++ 截屏

c++ - fwrite 输出字符串不正确

javascript - 比较两个对象数组并向匹配的对象添加新属性

php - 从数组列表创建数组树

arrays - 接受任意大小的静态数组的函数 (D)

java - 创建一个 ArrayList 的 ArrayList,与另一个 ArrayList 的 ArrayList 相比,该 ArrayList 具有一个附加元素

c++ - 重载可变参数函数,返回类型取决于参数数量

c++ - 输入参数类型 "const double *&"是什么意思?

java - 我们什么时候应该修改通过引用传递的对象?

python - 如何通过 Python 使用 COM INetCfg 对象?