简体   繁体   English

如何通过函数C ++传递字符串

[英]how to pass a string through a function c++

I'm just learning programming in c++. 我只是在学习C ++编程。 In my homework I need to compare three strings given by the user by a prompt. 在我的作业中,我需要根据提示比较用户给出的三个字符串。 I know that for a function to modify certain values directly instead of returning a value I need to use pointers. 我知道对于要直接修改某些值而不是返回值的函数,我需要使用指针。 I also know that strings already behave like pointers. 我也知道字符串已经像指针一样。 This is my code so far but I don't know where I'm wrong: 到目前为止,这是我的代码,但我不知道我哪里写错了:

#include"std_lib_facilities.h"

void switching (string x, string y){
        string flag;
        if (x>y){flag=y;
                y=x;
                x=flag;
        }

}

int main(){
        string  s1, s2, s3;
        cout<<"introduce three words: ";
        cin>>s1>>s2>>s3;
                switching(s1,s2);
                cout<<s1<<" "<<s2<<" "<<s3;
                cout<<endl;
                switching(s2,s3);
                cout<<s1<<" "<<s2<<" "<<s3;
                cout<<endl;
                switching(s1,s2);
                cout<<s1<<" "<<s2<<" "<<s3;
                cout<<endl;
        return 0;
}

Your function is receiving the strings by value (copies), not by reference (or pointer), so it can't actually perform the swap you're trying to do. 您的函数按值(副本)而不是按引用(或指针)接收字符串,因此它实际上无法执行您尝试执行的交换。 Receive the parameters by reference instead by changing the prototype to: 通过引用接收参数,而不是将原型更改为:

void switching (string& x, string& y){

For the record, while string s wrap pointers to char arrays, they behave like values, not pointers; 为了记录起见,当string s包装指向char数组的指针时,它们的行为类似于值,而不是指针。 if you receive them by value, they will allocate a new block of memory and copy the complete contents of the string into it. 如果按值接收它们,它们将分配一个新的内存块并将字符串的完整内容复制到其中。 That's why you want reference semantics if at all possible; 这就是为什么要尽可能使用引用语义的原因。 otherwise, you're making a lot of needless copies. 否则,您将制作许多不必要的副本。 You might be thinking of C style string literals and char arrays, which do get passed around as pointers to their first character, but that doesn't apply to true C++ std::string s. 您可能会想到C样式字符串文字和char数组,它们确实会作为指向第一个字符的指针而传递,但这不适用于真正的C ++ std::string

You can also avoid the explicit temporary flag object using std::swap from <utility> ( <algorithm> if you're not on C++11, but you really should be on C++11 by now; writing pre-C++11 C++ is just needlessly masochistic at this point): 您也可以使用<utility><algorithm> std::swap避免显式的临时flag对象,如果您不在C ++ 11上,但是现在您确实应该在C ++ 11上;编写pre-C ++ 11 C ++在这一点上是不必要的受虐狂):

void switching (string& x, string& y){
    if (x>y) std::swap(x, y);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM