为何这个程序输入q不终止输入
为什么这个程序输入q不终止输入?
下面的程序是将 一个字符串转成大写,以输入Q与q结束输入。为什么输入Q与q不能终止?
------解决方案--------------------
getline(cin, name, 'e')
因为getline里你设定参数以输入字母e结束输入的,所以输入q后,还得再输入个e,然后才能结束输入进行判断。
你输入qe应该就能退出了
------解决方案--------------------
while(x[i] != '\0')//不应该用'\0'来判断string的结束
------解决方案--------------------
下面的程序是将 一个字符串转成大写,以输入Q与q结束输入。为什么输入Q与q不能终止?
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
void change(string &x);
int main()
{
string name;
cout<<"Please enter a string (q to quit): ";
while(getline(cin, name, 'e') && name!= "q" && name !="Q" )
{
char ch;
ch = cin.get();
change(name);
cout<<"Another string: ";
}
return 0;
}
void change(string &x)
{
int i = 0;
while(x[i] != '\0')
{
x[i] = toupper(x[i]);
i++;
}
cout<<x<<endl;
}
------解决方案--------------------
getline(cin, name, 'e')
因为getline里你设定参数以输入字母e结束输入的,所以输入q后,还得再输入个e,然后才能结束输入进行判断。
你输入qe应该就能退出了
------解决方案--------------------
while(x[i] != '\0')//不应该用'\0'来判断string的结束
------解决方案--------------------
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
while (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
while (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。