我编写的代码有一个选项,用户输入一些数字,另一个选项将用户的两个数字相乘,所有这些都是在 2 种情况下生成的,但我得到了错误。我对编程完全陌生,只是为了清楚。
struct proizvod
{
char materijal;
int k; // kolicina
int c; // cijena
};
int main()
{
int izbor;
cout << endl
<< " 1 - Unos podataka.\n"
<< " 2 - Rezultat.\n"
<< " 3 - Izlaz.\n"
<< " Unesi broj i pritisni enter: ";
cin >> izbor;
switch(izbor)
{
proizvod p;
case 1:
cout << "\nUnesite ime proizvoda: ";
cin.get(p.materijal);
cout << "\nUnesite kolicinu proizvoda: ";
cin >> p.k;
cout << "\nUnesite cijenu proizvoda: ";
cin >> p.c;
break;
case 2:
int r;
r = p.k * p.c; // multiply
while (izbor!= 3);
}
return 0;
}
编辑
Error C2086 'int r': redefinition ConsoleApplication1
最佳答案
你的代码有几个问题:
- 如果用户输入 1 你会读到一个 char 但你会得到你在字符 1 之后输入的返回值以完成
cin >> izbor 的输入;
(或在 1) 之后输入的任何字符 - 如果用户输入 2,您使用非初始化值执行
p.k * p.c
,则行为未定义 - 仍然在用户输入 2 的情况下执行循环
while (izbor!= 3);
永远不会结束,因为 izbor 值为 2 并且不能更改为值 3 . - 另请注意 r 已设置但从未使用过。
如果我理解你的希望,你想要这样的东西,仍然只使用 char 作为 proizvod 甚至可能你想要一个 string :
#include <iostream>
using namespace std;
struct proizvod
{
char materijal;
int k; // kolicina
int c; // cijena
};
int main()
{
proizvod p;
bool pSet = false;
for (;;) {
cout << endl
<< " 1 - Unos podataka.\n"
<< " 2 - Rezultat.\n"
<< " 3 - Izlaz.\n"
<< " Unesi broj i pritisni enter: ";
int izbor;
if (!(cin >> izbor)) {
cerr << "the choice is not an integer, abort" << endl;
return -1;
}
switch (izbor) {
case 1:
cout << "\nUnesite ime proizvoda: ";
if (!(cin >> p.materijal)) {
cerr << "premature EOF" << endl;
return -1;
}
cout << "\nUnesite kolicinu proizvoda: ";
if (!(cin >> p.k)) {
cerr << "quantity is not an integer, abort" << endl;
return -1;
}
cout << "\nUnesite cijenu proizvoda: ";
if (!(cin >> p.c)) {
cerr << "price not an integer, abort" << endl;
return -1;
}
pSet = true;
break;
case 2:
if (!pSet)
cerr << "you did not enter the price and quantity" << endl;
else
cout << "Rezultat : " << p.k * p.c << endl;
break;
case 3:
return 0;
default:
cerr << "invalid choice" << endl;
}
}
return 0; // cannot be reach
}
为了不冒险,我宁愿用英文来写新句子
编译和执行:
pi@raspberrypi:/tmp $ g++ -g -pedantic -Wextra -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
1 - Unos podataka.
2 - Rezultat.
3 - Izlaz.
Unesi broj i pritisni enter: aze
the choice is not an integer, abort
pi@raspberrypi:/tmp $ ./a.out
1 - Unos podataka.
2 - Rezultat.
3 - Izlaz.
Unesi broj i pritisni enter: 4
invalid choice
1 - Unos podataka.
2 - Rezultat.
3 - Izlaz.
Unesi broj i pritisni enter: 2
you did not enter the price and quantity
1 - Unos podataka.
2 - Rezultat.
3 - Izlaz.
Unesi broj i pritisni enter: 1
Unesite ime proizvoda: a
Unesite kolicinu proizvoda: 2
Unesite cijenu proizvoda: 33
1 - Unos podataka.
2 - Rezultat.
3 - Izlaz.
Unesi broj i pritisni enter: 2
Rezultat : 66
1 - Unos podataka.
2 - Rezultat.
3 - Izlaz.
Unesi broj i pritisni enter: 3
pi@raspberrypi:/tmp $
如您所见,我还检查了 cin >>
是否成功,如果出现错误,我只是中止执行,但也可以刷新无效输入以重做。
关于c++ - 在编译时获取未初始化的内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56709666/