如何从函数返回字符串
How to return a string from a function?
我编写这个小程序只是为了更好地理解如何处理字符串。但我遇到了一个小问题。代码如下:
#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]
之后,长度仍然为零。您很幸运,没有产生访问冲突!
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- C 字符串返回字符串的整数/双精度/长整型值
- 如何从COM模块中的函数返回字符串数组?
- React Native (Android):无法通过 JNI 在 jobject 中返回字符串
- 我如何在函数 cpp 中返回字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 格式化返回字符串C++
- 返回字符串vs通过引用传递字符串以更新值
- 如何在不使用 STL 的情况下从函数反转字符串后返回字符串C++?
- 使用 ctypes 从函数返回字符串C++会给出大的 int,而不是 char 指针
- 从 C++ 中的模板函数返回字符串和整数
- 返回字符串的散点回文计数
- C++重载字符串 [] 运算符以返回字符串和
- 返回字符串和不同向量数据类型的映射C++
- 字符串函数不返回字符串? C++
- 从函数返回字符串C++错误
- 如何在返回字符串的函数中不忽略void值
- 我想将字符串转换为 Json 格式并返回字符串向量作为答案
- C - 返回字符串时的分割故障
- 使用向量和字符串函数返回字符串