簡體   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