Reputation: 21
I am very new to C++ code and when I input anything but a number for any cin
it automatically executes the rest of the cout
.
Basically, if I wanted to name the first fruit "Apple", it would execute all of the other cout
. If I named it only with numbers the other cout
would be fine.
#include "stdafx.h"
#include <iostream>
using namespace std;
struct Fruit {
char Name;
double Weight;
int Calories;
};
int main(){
struct Fruit TodaysFruit;
struct Fruit FruitA;
struct Fruit FruitB;
struct Fruit FruitC;
struct Fruit FruitD;
struct Fruit FruitE;
cout << "Enter Name For Fruit" << endl;
cin >> FruitA.Name;
cout << "Enter Weight For Fruit" << endl;
cin >> FruitA.Weight;
cout << "Enter Calories for Fruit" << endl;
cin >> FruitA.Calories;
//break
cout << "Enter Name For Fruit" << endl;
cin >> FruitB.Name;
cout << "Enter Weight For Fruit" << endl;
cin >> FruitB.Weight;
cout << "Enter Calories for Fruit" << endl;
cin >> FruitB.Calories;
//break
cout << "Enter Name For Fruit" << endl;
cin >> FruitC.Name;
cout << "Enter Weight For Fruit" << endl;
cin >> FruitC.Weight;
cout << "Enter Calories for Fruit" << endl;
cin >> FruitC.Calories;
return 0;
};
Upvotes: 1
Views: 354
Reputation: 26703
If you input "Apple" for
cin >> FruitA.Name;
Then "A" will go into the single character Name
in your struct.
"pple" will remain in input stream and will fail to be read into all the following numbers, causing the input stream to go into error state and all subsequent reads will fail (credits Pete Becker).
To fix, replace
char Name;
with
std::string Name;
You need to #include <string>
to support that (credits Ap31).
The std::
(a good input by Peter, credits) will make sure that the intended string is used, even if any active using
would make confusion possible.
Upvotes: 7