首页 > 解决方案 > 如何在 C++ 中实现字符输入验证

问题描述

我需要创建一个程序来计算正在构建的表格的价格。

main() 函数应调用以下函数:

  1. 一种功能,它接受标准的与桌子一起使用的椅子数量。

  2. 接受标准的表表面积(以 m2 为单位)的函数。

  3. 接受标准的用于建造桌椅的木材类型的功能;“m”代表桃花心木,“o”代表橡木,“p”代表松木。理想情况下,任何其他条目都应被拒绝。

  4. 一个函数,它采用椅子的数量 (N)、桌子的表面积 (S) 和木材的类型 (x) 来计算价格。一张桌子的价格是 x(S + 1/2N),其中松木、橡木和桃花心木的 x 分别为 50 美元、100 美元和 150 美元。

  5. 显示购买详情的功能。

目前结果:

目前我的代码只会计算带有'm'(桃花心木)而不是其他两种材料的桌子的价格。例如:

Number of chairs: 5
Surface area of table (m2): 5
Wood type: m
Total = 1125

如果我将木材类型更改为“o”或“p”,将产生相同的价格。

代码:

#include <iostream>

using namespace std;

int main(){
int N;
cout << "Number of chairs: ";
cin >> N;

int S;
cout << "Surface area (in meters squared) of the table: ";
cin >> S;

cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
char x;
cin >> x;

while(x != 'm' && x != 'o' && x != 'p'){
    cout << "Error. Invalid input. Please try again" << endl;
    cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
    cin >> x;
}

int total;
if(x = 'm'){
    total = 150*(S + (0.5*N));
} else if(x = 'o'){
    total = 100*(S + (0.5*N));
} else if(x = 'p'){
    total = 50*(S + (0.5*N));
}

cout << "--------------------\n";
cout << "Details of purchase:\n";
cout << "--------------------\n";
cout << "Number of chairs: " << N << endl;
cout << "Surface area of table (m2): " << S << endl;
cout << "Wood type: " << x << endl;
cout << "Total = " << total << endl;

return 0;
}

标签: c++

解决方案


#include <iostream>
using namespace std;
int main(){
    float N;
    cout << "Number of chairs: ";
    cin >> N;
    float S;
    cout << "Surface area (in meters squared) of the table: ";
    cin >> S;
    cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
    char x;
    cin >> x;
    while(x != 'm' && x != 'o' && x != 'p'){
        cout << "Error. Invalid input. Please try again" << endl;
        cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
        cin >> x;
    }
    float total=0.f;
    if(x == 'm'){
        total = 150.f*(S + (0.5f*N));
    } else if(x == 'o'){
        total = 100.f*(S + (0.5f*N));
    } else if(x == 'p'){
        total = 50.f*(S + (0.5f*N));
    }
    cout << "--------------------\n";
    cout << "Details of purchase:\n";
    cout << "--------------------\n";
    cout << "Number of chairs: " << N << endl;
    cout << "Surface area of table (m2): " << S << endl;
    cout << "Wood type: " << x << endl;
    cout << "Total = " << total << endl;
    return 0;
}

推荐阅读