繁体   English   中英

在C ++中返回字符串变量

[英]Returning a string variable in C++

为了方便起见,我试图创建一个不区分大小写的基本用户界面。 为此,我制作了一个转换器类,使字符串变为大写,但是我偶然发现了一个问题。 使用该类之后,main()中的if语句应该解释来自转换器的消息,但是它只读取原始输入是什么,而不是大写输入,并且我尝试直接从转换器,但不会让我。

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

string response;

//converts responses to upper-case
void convert(string response) {
    for (int i = 0; i < response.length(); i++) {
        response[i] = toupper(response[i]);
    }
}

//main dialogue
int main() {

    cout << "How are you?: ";
    getline(cin, response);
    convert(response);
    if (response == "GOOD") {
        cout << "Response 1./l";
    }
        else {
        cout << "Response 2./l";
    }
}

我对C ++还是很陌生,所以对于错误很容易解决或难以理解解决方案,我深表歉意。

查找“按值传递”和“按引用传递”-您具有“按值传递”,但是期望“按引用传递”

在C ++中: void convert(string& response) {

在您的情况下,事情有点“奇怪”,因为正如@NeilLocketz的注释中指出的那样,您有一个全局response ,即方法中的本地response -实际上是全局response ,因为您将其用作调用参数。 如果您想正确地做事,您可能不希望response是全球性的。

请注意,接受的答案仍然具有比此更多的内存副本。 真正的关键是理解按值传递和按引用传递并使用适合您情况的任何一种。

除了需要传递引用而不是值之外,您还应尝试使用C ++-11功能:

void convert(string &response) {
    for (auto &c: response) {
         c = toupper(c);
    }
}

它更干净,更简单。

另一个选择是更改函数头,使其返回string 那是:

string convert(const string &inResponse) {
    string outResponse(inResponse);
    for (int i = 0; i < inResponse.length(); i++) {
        outResponse[i] = toupper(inResponse[i]);
    }
    return outResponse;
}

然后在主函数中使用返回的字符串,例如:

....
// response is input, outputResponse is output:
string outputResponse = convert(response);
....

暂无
暂无

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

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