【发布时间】:2017-02-07 08:56:13
【问题描述】:
在这个相当简单的练习中,我必须接收用户输入,将所述输入存储到字符串中,通过引用将字符串传递给函数,最后修改字符串以便每个字符都被 toupper() 函数“解析” . 但是,如果用户插入“q”作为输入,程序就会停止说“Bye”,或者如果他只是按下 Enter 键,程序应该会说“嘿,这个字符串是空的”。 现在真正的问题在最后一部分,因为我的代码无法管理用户仅输入 Enter Key 值的情况(老实说,即使我只是在输入一堆空格后跟 Enter Key,也没有任何反应)
void uppercase(std::string &);
int main(){
using namespace std;
string ex2;
cout << "Exercise 2" <<endl;
while(ex2!="Bye"){
cout << "Enter a string(q to quit): ";
cin >> ex2;
cout << "Was: " << ex2 << endl << "Now is: ";
uppercase(ex2);
}
return 0;
}
void uppercase(std::string &str){
using namespace std;
if(str[0]=='\n')
cout <<"Empty string dude!" << endl;
else{
if(str.length()==1 && str[0]=='q'){ //press 'q' to exit program
str="Bye";
cout << str;
}
else{ //uppercase
for(int i=0;i<str.length();i++){
str[i]=(toupper(str[i]));
}
cout << str <<endl;
}
}
}
我还尝试了 compare() 函数,甚至将整个字符串与 null(毫无意义,但仍然值得一试)和字符串 "";
【问题讨论】:
-
只检查输入的空字符串:
if(str.empty()) -
cin >> ex2看不到进入。它是空白并被丢弃。查看std::getline -
@user4581301 你说得对。我使用了 getline(cin,ex2) 并将 if 语句修改为 if(str[0]=='\0') ,现在它可以工作了!
-
接受@πάνταῥεῖ 的建议并使用
empty。第一,它更容易阅读,第二,它可以捕捉到测试 '\0' 可能会遗漏的一些极端情况。我不认为在 C++ 11 标准之前空终止是强制性的。 -
我使用了 empty() 函数和 getline(cin,string) 函数(empty() 在没有 getline() 函数的情况下无法工作)并且运行流畅。谢谢!