从c ++函数返回一个字符串 [英] returning a string from a c++ function
问题描述
我是一名初学者,我一直在阅读一本关于C ++的书,并且我正在讨论函数的一章。我写了一个反转字符串,将它的一个副本返回给main并输出它。
字符串reverseInput(字符串输入);
int main()
{
string input =Test string;
// cin>> input;
cout<< reverseInput(input);
返回0;
}
字符串reverseInput(字符串输入)
{
字符串反转=输入;
int count = input.length();
for(int i = input.length(),j = 0; i> = 0; i--,j ++){
reverse [j] = input [i-1];
}
返回反向;
}
以上似乎可行。当我更改以下代码时,会发生问题:
string input =Test string;
到:
字符串输入;
cin>> input;
在此更改之后,反转函数仅返回第一个输入单词的反转,而不是整个串。我无法弄清楚自己出错的地方。
最后,有没有一种更优雅的方法可以通过使用引用来完成,而不需要复制输入,所以输入变量本身是被修改的?问题出在 cin
。它会在读取第一个空格字符后停止读取。
请参阅本教程的cin和strings部分: http://www.cplusplus.com/doc/tutorial/basic_io/
您可以使用 getline(cin,input);
做你想做的事。
I'm a beginner and I've been going through a book on C++, and I'm on a chapter on functions. I wrote one to reverse a string, return a copy of it to main and output it.
string reverseInput(string input);
int main()
{
string input="Test string";
//cin>>input;
cout<<reverseInput(input);
return 0;
}
string reverseInput(string input)
{
string reverse=input;
int count=input.length();
for(int i=input.length(), j=0; i>=0; i--, j++){
reverse[j]=input[i-1];
}
return reverse;
}
The above seems to work. The problem occurs when I change the following code:
string input="Test string";
to:
string input;
cin>>input;
After this change, the reverse function returns only the reverse of the first inputted word, instead of the entire string. I can't figure out where I am going wrong.
Lastly, is there a more elegant way of doing this by using references, without making a copy of the input, so that the input variable itself is modified?
The problem is with cin
. It stops reading after the first space character is read.
See the "cin and strings" section of this tutorial: http://www.cplusplus.com/doc/tutorial/basic_io/
You can use getline(cin, input);
to do what you want.
这篇关于从c ++函数返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!