编译时收到未初始化的内存警告

Getting uninitialized memory warning at compilation

本文关键字:内存 警告 初始化 编译      更新时间:2023-10-16

我编写的代码有一个选项,用户输入一些数字和其他选项,将用户的两个数字相乘,所有这些都在 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;
}

编辑

错误 C2086 'int r': 重新定义控制台应用程序1

您的代码中存在几个问题:

如果用户输入 1,
  • 则您读取了一个字符,但您将获得在字符1 之后输入的返回符以完成cin >> izbor;的输入(或在 1 之后输入的任何字符)
  • 如果用户使用未初始化的值输入 2p.k * p.c,则行为未定义
  • 仍然以防用户输入 2,您执行永不结束的循环while (izbor!= 3);因为izbor值为 2 并且无法更改为值 3。
  • 另请注意,r已设置但从未使用。

如果我理解你的希望,你想要这样的东西,仍然只使用一个字符来表示proizvod,甚至可能你想要一个字符串

#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 >>成功,如果出现错误,我只是中止执行,但也可以刷新无效输入以重做。