我受命这样做:
“产品代码:(按Enter)
如果未输入产品代码,则系统仅显示另一个产品代码。
因此,基本上我可以选择输入产品代码或按Enter键,然后出现另一个产品代码,而我的问题是,如果用户选择按Enter键而不是输入代码,那么如何显示产品代码。
请注意,所有产品代码已经是程序的一部分,用户只需要输入产品代码即可更改其值。
int main(){
int productcode;
system("CLS");
cout << "Product Code : ";
cin >> productcode;
return 0;}
*尝试了Kanthan的建议后更新
我能够想到以下代码:
using namespace std;
int main()
{
int d;
int productcode;
int p1;
int d1;
float v1, gt;
char ans;
d1=0;
gt=v1=0;
d=26;
do{
char code[40];
system("CLS");
cout<< "Product code : ";
cin.getline(code,40,'\n');
productcode=atoi(code);
if(code[0]=='\0')
{
cout << '\n'<<"Random Product Code appears"<<'\n' << '\n';
system("PAUSE");
}
else if(productcode>410 && productcode<15059){
switch(productcode){
case 1001:
d1=1;
p1=0;
cout << '\n' << "Product Code : " << productcode << " - Product - Product Price Number of Cans: ";
cin >> p1;
if(p1==0){d1=0;v1=0;}
break;
case 15058:
system("CLS");
cout << "Items Purchased:" << '\n';
if(d1==1)
{
v1=p1*25;
cout << "1001 - Product - Product Price x " << p1 << " pc/s = " << v1 << '\n';
}
lines();
gt=v1;
cout << "Grand Total : " << gt << " USD" << '\n' << flush;
system("PAUSE");
system("PAUSE");
break;
case 8223:
int mrd;
mrd=3;
do{
system("CLS");
cout << "Are you sure that you want to go? Y/N: " << '\n';
cin >> ans;
if (ans=='Y'||ans=='y')
{
d=27;
mrd=4;
cout << '\n' << "Your total sales is " << gt << " USD." << '\n';
system("PAUSE");
}
else if (ans=='N'||ans=='n')
{
mrd=4;
cout << '\n' << "Your total sales is at " << gt << " USD." << '\n' << flush;
system("PAUSE");
}
else
{
system("CLS");
cout << "Wrong input. Please try again." << '\n' << flush;
system("PAUSE");
}
}while(mrd<4);
break;
default:
system("CLS");
cout << "Product Code input is incorrect. Please try again." <<'\n' << flush;
system("PAUSE");
break;
}
}
else {
system("CLS");
cout << "Product Code input is incorrect. Please try again." <<'\n' << flush;
system("PAUSE");
}
}while(d<27);
}
我现在的问题是即使代码[0] =='\ 0'不正确,“随机产品代码出现”仍然显示。
答案 0 :(得分:0)
您可以做这样的事情
#include <iostream>
#include <stdlib.h>
int myisdigit(const char *str);
int main()
{
char str[40];
int code;
std::cout<<"Enter Product code:";
std::cin.getline(str,40,'\n');
if(str[0]=='\0')
{
std::cout<<"Next Product";
}
else
{
if(!myisdigit(str))
{
std::cout<<"Enter Proper Code";
exit(1);
}
code=atoi(str);
std::cout<<"Product Number:"<<code;
}
}
int myisdigit(const char *str)
{
while(*str)
{
if( ! ( ( ( *str ) >= '0' ) && ( (*str) <='9' ) ) )
return 0;
str++;
}
return 1;
}
或者,如果您想使用std::string
,请在代码中进行一些更改,例如
std::string mystr;
int code;
const char *str;
std::cout<<"Enter Product code:";
std::getline(std::cin,mystr);
str=mystr.c_str();