2016-12-16 88 views
1

爲了方便起見,我試圖製作一個不區分大小寫的基本用戶界面。爲此,我創建了一個轉換器類,使字符串大寫,但我偶然發現了一個問題。在使用該類之後,main()中的if語句應該解釋來自轉換器的消息,但它只讀取原始輸入的內容,而不是大寫的對應內容,並且我試圖直接從轉換器,但它不會讓我。在C++中返回一個字符串變量

#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++,所以我道歉,如果這個錯誤是一個容易解決,或者我很難理解的解決方案。

回答

1

另一種選擇是更改函數標題,以便返回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); 
.... 
+0

@ John3136關於儘可能避免複製的好處。 – NoseKnowsAll

+0

我不知道類可以被識別爲字符串,這可能會解決我的問題。最後,我把getline(cin,response);在轉換器本身,只要我需要響應就叫轉換器。 – Zyxlm

+1

'我不知道類可以被識別爲字符串'這是什麼意思?現在你有了修改的輸入 - 那就是軟件工程。這裏介紹了幾種可行的解決方案,但是你忽略了它們全部? – John3136

2

查找「按值傳遞」和「按引用傳遞」 - 你有「按值​​傳遞」,但你期待

在C++「按引用傳遞」:void convert(string& response) {

你的情況的東西有點「奇怪」,因爲正如在@NeilLocketz的評論中指出的那樣,在方法中你有一個全局的response,本地的response--它實際上是全局的,因爲你使用它作爲調用參數。如果你想正確地做事,你可能不希望response成爲全球性的。

請注意,接受的答案仍然有比這更多的內存副本。真正的關鍵是理解按價值傳遞和通過參考,並根據您的情況選擇適合的值。

+1

他也影響了全球響應 –

+0

@NeilLocketz非常好的一點(我完全錯過了;-) – John3136

2

除了需要傳遞一個參考,而不是一個值,你應該嘗試使用C++ - 11功能:

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

它更清潔,更簡單。