我的函数 return 正在打印到控制台,它只会在我调用它时每隔一段时间工作 C++
My function's return is printing to the console and it will only work every other time I call it C++
我只是在玩 C++,并决定制作一个基于文本的角色扮演游戏。我创建了一个方法来从用户那里获取信息并将其更改为小写。这是函数:
std::string getInfo_ToLower(std::string whatToSay) {
std::string a = "";
std::cout << whatToSay << std::endl;
getline(std::cin, a);
for(int i = 0; i < a.length(); i++){
a[i] = putchar(tolower(a[i]));
}
return a;
};
如果有帮助,我正在研究 Xcode。那么,是否有任何原因表明此方法只能在我每隔一次调用它时才起作用,并且我的 "return a;" 正在打印到控制台是否有任何原因?
谢谢。
您的代码在遍历字符串 a
时调用 putchar
,但结果是 buffered。如果您希望它立即可见,请添加 fflush
:
的调用
for(int i = 0; i < a.length(); i++){
a[i] = putchar(tolower(a[i]));
}
fflush(stdout);
return a;
请注意,您同时进行打印和转换的方式非常不直观。您最好单独打印结果,如下所示:
// There are better ways to do this, but just to illustrate the point
// let's keep the loop in place
for(int i = 0; i < a.length(); i++){
a[i] = tolower(a[i]);
}
cout << a << flush;
return a;
为什么一定要用put char?
cout 不是更好吗?
for(int i = 0; i < a.length(); i++){
a[i] = tolower(a[i]);
}
std::cout << a <<std::endl;
我只是在玩 C++,并决定制作一个基于文本的角色扮演游戏。我创建了一个方法来从用户那里获取信息并将其更改为小写。这是函数:
std::string getInfo_ToLower(std::string whatToSay) {
std::string a = "";
std::cout << whatToSay << std::endl;
getline(std::cin, a);
for(int i = 0; i < a.length(); i++){
a[i] = putchar(tolower(a[i]));
}
return a;
};
如果有帮助,我正在研究 Xcode。那么,是否有任何原因表明此方法只能在我每隔一次调用它时才起作用,并且我的 "return a;" 正在打印到控制台是否有任何原因?
谢谢。
您的代码在遍历字符串 a
时调用 putchar
,但结果是 buffered。如果您希望它立即可见,请添加 fflush
:
for(int i = 0; i < a.length(); i++){
a[i] = putchar(tolower(a[i]));
}
fflush(stdout);
return a;
请注意,您同时进行打印和转换的方式非常不直观。您最好单独打印结果,如下所示:
// There are better ways to do this, but just to illustrate the point
// let's keep the loop in place
for(int i = 0; i < a.length(); i++){
a[i] = tolower(a[i]);
}
cout << a << flush;
return a;
为什么一定要用put char? cout 不是更好吗?
for(int i = 0; i < a.length(); i++){
a[i] = tolower(a[i]);
}
std::cout << a <<std::endl;