【发布时间】:2021-06-11 14:36:31
【问题描述】:
您好,我正在解决 Stanely 的《C++ Primer》一书的问题。问题如下:-
编写一个程序来读取两个字符串并报告是否 字符串相等。如果不是,请报告两者中哪个更大。现在,改变 程序报告字符串是否具有相同的长度,如果 不是,报告哪个更长。
我使用变量选择在程序之间切换,即是否检查字符串是否相等。或者检查字符串是否具有相同的长度。
#include<iostream>
using namespace std;
int main(){
char choice;
cout<<"Please enter choice"<<endl<<"For Larger press (L) and for longer press (l) "<<endl;
cin>>choice;
string s1, s2 ;
getline(cin,s1);
getline(cin,s2);
if(choice=='L'){
if(s1!=s2){
if(s1>s2) {
cout << "string which is larger is : " <<s1<<endl;
}
else{
cout<<"string which is larger is : " <<s2<<endl;
}
}
else{
cout<<"Both strings are equal "<<endl ;
}
}
else if (choice == 'l'){
if(s1.size() != s2.size()){
if(s2.size()> s1.size()){
cout<<"Longer string : "<<s2<<endl;
}
else {
cout<<"Longer string : " << s1<<endl;
}
}
else {
cout<<"Both strings have same length" <<endl;
}
}
else{
cerr<<"wrong input!! "<<endl;
return -1;
}
return 0;
}
但是当我在编译程序时,它只接受字符串 s1 的输入,而不接受字符串 s2 的输入。
输出如下:-
【问题讨论】:
-
调试器。使用调试器的绝佳示例。调试器允许您单步执行程序,观察变量。
-
只接受字符串 s1 的输入,不接受字符串 s2 的输入。 你确定吗?我期望相反:
s1始终是一个空字符串,s2是唯一可以输入的。原因很简单。要输入choice,您必须使用 ENTER 确认,但cin >> choice;会将其留在输入缓冲区中。然后,如果你调用getline(cin,s1);,它会立即被消耗——在s1中留下一个空字符串。 -
打印消息以查看您实际要求这两个字符串的位置。
cout << "Enter string one: "; getline(cin,s1); cout << "Enter string two: "; getline(cin,s2); -
要解决这个问题,您应该调查std::istream::ignore。 (当然,@ThomasMatthews 的调试提示也是值得的。)