为了方便起见,我试图创建一个不区分大小写的基本用户界面。为此,我创建了一个转换器类,使字符串大写,但我偶然发现了一个问题。在使用该类之后,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 ++很新,所以如果错误很容易解决,或者我很难理解解决方案,我会道歉。
答案 0 :(得分:2)
查找&#34;通过值&#34;并且&#34;通过引用传递&#34; - 你有&#34;通过价值&#34;但是你期待&#34;通过引用传递&#34;
在C ++中:void convert(string& response) {
在你的情况下,事情有点轻微&#34;奇怪&#34;因为@NeilLocketz在评论中指出,你有一个全局response
,方法中的本地response
- 实际上是全局的,因为你使用它作为调用参数。如果您想要正确地做事,您可能不希望response
成为全球性的。
请注意,接受的答案仍然拥有比此更多的内存副本。真正的关键是理解价值传递并通过引用传递,并使用适合您情况的任何一种。
答案 1 :(得分:2)
除了需要传递引用而不是值之外,您应该尝试使用C ++ - 11功能:
void convert(string &response) {
for (auto &c: response) {
c = toupper(c);
}
}
它更清洁,更简单。
答案 2 :(得分: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);
....