简体   繁体   中英

Returning a string variable in C++

I'm attempting to make a basic user interface that is not case-sensitive for the sake of convenience. To do this, I've made a converter class that makes the string uppercase, but I've stumbled on an issue. After using the class, an if statement in main() is supposed to interpret the message from the converter, but it only reads what the original input was, not it's uppercase counterpart, and I've attempted to return the converted string directly from the converter, but it will not let me.

#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";
    }
}

I'm very new to C++, so I apologize if the mistake was an easy one to fix or if I have difficulty understanding the solution.

Look up "pass by value" and "pass by reference" - you have "pass by value" but you are expecting "pass by reference"

In C++: void convert(string& response) {

In your case things are slightly "odd" because as pointed out in the comments by @NeilLocketz, you have a global response , the local response in the method - which is actually the global one since you use that as the calling parameter. If you want to do things properly, you probably don't want response to be global.

Note that the accepted answer still has more memory copies than this. The real key is to understand pass by value and pass by reference and use whichever one is appropriate to your circumstances.

Aside from the need to pass a reference instead of a value, you should try to use C++-11 features:

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

it is much cleaner, and simpler.

Another option is to change your function header so that it returns a string . That is:

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

And then you use the returned string in your main function like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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