Reputation: 13
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.
Upvotes: 1
Views: 98
Reputation: 29265
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.
Upvotes: 2
Reputation: 4624
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);
....
Upvotes: 1
Reputation: 4481
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.
Upvotes: 2