【发布时间】:2021-08-14 06:30:32
【问题描述】:
好的,我有一个我正在尝试制作的程序,基本的事情是防止我在整个项目中一遍又一遍地重写相同的长 4 行代码,我想看看我能不能得到它从 cin 获取一个字符串并将整个字符串变为小写(我知道转换方法,但这样我就不必编写真正长度的 if 语句)并返回该字符串以用作其他中的变量部分程序或其他功能。
我不知道我是否只需要让函数在主块中返回变量本身还是什么。我对 c++ 和一般编码很陌生,如果它可能的 id 喜欢在字符串中包含空格。再说一次,我在 c++ 方面并没有太多经验,所以我想知道它是否可能,如果是最好的方法。
这是我目前所拥有的
int loAns() {
string lAnswer; //Makes the lAnswer, a string used for a long answer that a char wouldn't do properly
cin >> lAnswer; //User enters it
// using transform() function and ::tolower
transform(lAnswer.begin(), lAnswer.end(), lAnswer.begin(), ::tolower); //The transform and ::tolower to make it uniform
cout << lAnswer << endl; //Outputs the lAnswer to console
return 0; //This is where I'm assuming the variable gets put to be used in the rest of the program
}
【问题讨论】:
-
返回
lAnswer而不是0,改变函数的返回类型。 -
建议:传入对流的引用
string loAns(istream & in),以便您可以将此函数用于文件和所有其他类型的流。使您不必再次编写此函数。也值得测试in >> lAnswer;以确保它成功。您迟早不检查的错误最终会成为您必须寻找的错误。
标签: c++ string function return-value tolower