如何从函数返回字符串

How to return a string from a function?

本文关键字:返回 字符串 函数      更新时间:2023-10-16

我编写这个小程序只是为了更好地理解如何处理字符串。但我遇到了一个小问题。代码如下:

#include<iostream>
#include<string>
using namespace std;
string& add( string&x ){
    string t; // <=  Is this the problem???Declaring local string variable
    cout <<"Size of String :" <<x.size() << endl;
    for(int i=0; i<x.size();i++){
        int  n = x[i] - '0';
        t[i] = n + 2  + '0';
    }
    for(int i=0;i<x.size();i++)
       cout <<"t["<<i<<"]="<<t[i]<<endl;    //This line is showing output as I wanted
    cout <<"nt = " << t << endl;           // <=why the output of this line is blank?
    cout <<"size of t="<<t.size() << endl;  // <=and why the size of string t is zero?              
    return t;         
}
int main(){
   string a;
   cin >> a ;
   string b = add(a);
   cout << "b =" << b << endl;
   system("pause");
   return 0; 
}

I/p: 123

o/p:

size:3

t[0]=3 t[1]=4 t[2]=5

t =

size = 0

b =

我有引用变量的问题,传递字符串作为引用并返回字符串。有人能帮帮我吗?

是的,这是一个问题。最终得到一个悬空引用。在退出函数时,局部string t被销毁,返回的引用最终引用恰好位于t所在的内存位置的任何内容。以后使用它会导致未定义的行为。

按值返回字符串

string add( /* const */ string&x ) // should use `const` probably if you don't modify x

编译器足够聪明,可以避免不必要的复制(参见copy省略)。

PS:应该使用+=运算符将char附加到字符串后,即将t[i] = n + 2 + '0';替换为t[i] += n + 2 + '0';std::string是一个类,[]操作符用于从一个初始化的字符串中读写(你不能通过增加计数器超过字符串的末尾来追加,并且你的初始字符串的长度为0),使用它的重载操作符+=来追加。

我相信使用像itoa和atoi这样有用的函数是在整数和字符串之间进行转换的最好方法,而且它也很容易。

#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
string add( char * x ){
    int n = atoi(x) + 2;
    char m[10];
    itoa(n, m, 10);
    return m;      
}
int main(){
char a[10];
cin >> a ;
string b = add(a);
cout << "b =" << b << endl;
system("pause");
return 0; 
}

string t;声明之后,t是空字符串。所以你不允许给t[0],t[1]等赋值——它们不存在。(从技术上讲,t[0]作为t.cstr()的空终止符存在,但我们不去那里。)

在非法赋值给t[i]之后,长度仍然为零。您很幸运,没有产生访问冲突!