Can you help me to solve errors in this code? [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I started studying C ++ recently and I'm trying to create a "calculator" with a few operations.
But I'm stuck in string 26 (cin >> choose;), which seems unresponsive. Why?
//CALCULATOR
#include <iostream>
using namespace std;
int main()
{
int start;
int choose;
int first;
int second;
int unic;
int result;
cout << "CALCULATOR (2 values)" << endl;
cout << "Click a botton to continue: " << endl;
cin >> start;
cout << "Write: " << endl;
cout << "- '1' for sum" << endl;
cout << "- '2' for subtraction" << endl;
cout << "- '3' for moltiplication" << endl;
cout << "- '4' for power of 2" << endl;
cout << "Your answer: " << endl;
cin >> choose;
cout << "________________________" << endl;
{
if (choose=1, 2, 3)
cout << "Insert the first value: " << endl;
cin >> first;
cout << "Insert the second value: " << endl;
cin >> second;
{
if (choose=1)
result = first + second;
}
{
if (choose=2)
result = first + second;
}
{
if (choose=3)
result = first * second;
}
{
if (choose=4)
cout << "Insert the value: " << endl;
cin >> unic;
result = unic * unic;
}
}
cout << "Your result is: " << result;
}
It doesn't give me any errors, but it continues to execute all the "cout" operations I wrote, without giving me the possibility to write my values ​​with "cin".

There are several issues in your code,
In C++ = stands for assignment to check value equivalency you have to use ==
if (choose = 1, 2, 3){
...
// this doesn't work in C/C++
// change it into
if (choose == 1 || choose == 2 || choose == 3)
When you have more than one line of code under a conditional (if/else or loops for/while) you will need to explicitly block them inside curly braces. So that changes if first if block into this
if (choose == 1 || choose == 2 || choose == 3){
cout << "Insert the first value: " << endl;
cin >> first;
cout << "Insert the second value: " << endl;
cin >> second;
...
Same goes for the nested if condition.
Also there's no reason to take input for start.
If you fix all the errors you should get a code like this ->
//CALCULATOR
#include <iostream>
using namespace std;
int main()
{
int start;
int choose;
int first;
int second;
int unic;
int result;
cout << "CALCULATOR (2 values)" << endl;
cout << "Click a botton to continue: " << endl;
// cin >> start;
cout << "Write: " << endl;
cout << "- '1' for sum" << endl;
cout << "- '2' for subtraction" << endl;
cout << "- '3' for moltiplication" << endl;
cout << "- '4' for power of 2" << endl;
cout << "Your answer: " << endl;
cin >> choose;
cout << "________________________" << endl;
if (choose == 1 || choose == 2 || choose == 3){
cout << "Insert the first value: " << endl;
cin >> first;
cout << "Insert the second value: " << endl;
cin >> second;
if (choose == 1)
result = first + second;
if (choose == 2)
result = first + second;
if (choose == 3)
result = first * second;
}
if (choose == 4){
cout << "Insert the value: " << endl;
cin >> unic;
result = unic * unic;
}
cout << "Your result is: " << result << endl;
}
Footnote: Please use the given code as reference and try to understand the basics carefully. It is importat you do that.

Related

How I can use CASE in a different way? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Hello I am trying to build a project but the case '2' is not working.
struct student
{
string fname;//for student first name
string lname;//for student last name
string id;//for Registration No number
string course;//for class info
}studentData;//Variable of student type
struct teacher
{
string fname;//first name of teacher
string lname;//last name of teacher
string id;//Bool Group
string course;//Number of serves in School
}teach;//Variable of teacher type
int main()
{
int i = 0, j;//for processing usage
char choice;//for getting choice
string find;//for sorting
string srch;
while (1)//outer loop
{
system("cls");//Clear screen
//Level 1-Display process
cout << "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\";
cout << "\n\n\t\t\tSCHOOL MANAGEMENT PROGRAM\n\n";
cout << "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\";
cout << "\n\n\t\t\tMAIN SCREEN\n\n";
cout << "Enter your choice: " << endl;
cout << "1.Students information" << endl;
cout << "2.Teacher information" << endl;
cout << "3. Course information " << endl;
cout << "4. Display Strudent information " << endl;
cout << "5. Display Teacher Information " << endl;
cout << "6. Display Course Information n" << endl;
cout << "7.Exit program" << endl;
cin >> choice;
system("cls");//Clear screen
switch (choice)//First switch
{
case '1': //Student
{
{ ofstream f1("student.txt", ios::app);
for (i = 0; choice != 'n'; i++)
{
if ((choice == 'y') || (choice == 'Y') || (choice == '1'))
{
cout << "Enter First name: ";
cin >> studentData.fname;
cout << "Enter Last name: ";
cin >> studentData.lname;
cout << "Enter Registration number: ";
cin >> studentData.id;
cout << "Enter class: ";
cin >> studentData.course;
f1 << studentData.fname << endl << studentData.lname << endl << studentData.id << endl << studentData.course << endl;
cout << "Do you want to enter data: ";
cout << "Press Y for Continue and N to Finish: ";
cin >> choice;
}
}
f1.close();
}
continue;//control back to inner loop -1
continue;//Control pass to 1st loop
}
case '2'://Teachers biodata
{
{ ofstream t1("teacher.txt", ios::app);
for (i = 0; choice != 'n'; i++)
{
if ((choice == 'y') || (choice == 'Y') || (choice == '1'))
{
cout << "Enter First name: ";
cin >> teach.fname;
cout << "Enter Last name: ";
cin >> teach.lname;
cout << "Enter Registration number: ";
cin >> teach.id;
cout << "Enter class: ";
cin >> teach.course;
t1 << teach.fname << endl << teach.lname << endl << teach.id << endl << teach.course << endl;
cout << "Do you want to enter data: ";
cout << "Press Y for Continue and N to Finish: ";
cin >> choice;
}
}
t1.close();
continue;//control back to inner loop -1
}
continue;//Control pass to 1st loop
}
case '3':
{
{ ifstream f2("student.txt");
cout << "Enter First name to be displayed: ";
cin >> find;
cout << endl;
int notFound = 0;
for (j = 0; (j < i) || (!f2.eof()); j++)
{
getline(f2, studentData.fname);
if (studentData.fname == find)
{
notFound = 1;
cout << "First Name: " << studentData.fname << endl;
cout << "Last Name: " << studentData.lname << endl;
getline(f2, studentData.id);
cout << "Registration No number: " << studentData.id << endl;
getline(f2, studentData.course);
cout << "Class: " << studentData.course << endl << endl;
}
}
if (notFound == 0) {
cout << "No Record Found" << endl;
}
f2.close();
cout << "Press any key two times to proceed";
_getch();//To hold data on screen
_getch();//To hold data on screen
}
continue;//control back to inner loop -1
}
case '4':
{
{ ifstream t2("teacher.txt");
cout << "Enter First name to be displayed: ";
cin >> find;
cout << endl;
int notFound = 0;
for (j = 0; (j < i) || (!t2.eof()); j++)
{
getline(t2, studentData.fname);
if (studentData.fname == find)
{
notFound = 1;
cout << "First Name: " << studentData.fname << endl;
cout << "Last Name: " << studentData.lname << endl;
getline(t2, teach.id);
cout << "Registration No number: " << studentData.id << endl;
getline(t2, teach.course);
cout << "Class: " << studentData.course << endl << endl;
}
}
if (notFound == 0) {
cout << "No Record Found" << endl;
}
t2.close();
cout << "Press any key two times to proceed";
_getch();//To hold data on screen
_getch();//To hold data on screen
}
continue;//control back to inner loop -1
}
case '5':
{}
case '6':
{}
case '7':
{
break;//outer case 3
}//outer case 3
break;//outer loop
}
}
}
inside your switch statement, inside the case where you are checking if "choice" is '2 (case '2'://Teachers biodata), you have yet another if statement which checks if "choice" is '1', but at that point "choice" will be '2'.
if ((choice == 'y') || (choice == 'Y') || (choice == '1'))
becomes
if ((choice == 'y') || (choice == 'Y') || (choice == '2'))

Validate string input in c++ for letters and spaces only [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I haven't got to know a lot about functions yet since I'm just at chapter 4 (which is decision making using if, else) of Starting Out with C++ book.
Here my problem asks me to enter the inputs of runner names and their timer so I could rank them in 1st 2nd and 3rd place.
I'm having trouble to validate the input for the string for runners's names as letters and spaces only.
I'm thinking about using loop or bool but I don't know what is the proper way to put it.
Can somebody show me what function I can use best in this case without repeating step into multiple lines of codes.
I'm sorry in advance for my long version code, I'm also looking for the way to shorten it.
#include <iostream>
#include <string>
#include <iomanip> // for setw, setpresicion, control output
#include <cctype> // for getline, cin.
using namespace std;
int main()
{
string runner1, runner2, runner3;
double time1, time2, time3;
cout << "Enter Runner 1 name: ";
getline(cin, runner1);
cout << "Enter Runner 2 name: ";
getline(cin, runner2);
cout << "Enter Runner 3 name: ";
getline(cin, runner3);
cout << runner1 << "'s finishing time: ";
cin >> time1;
while (!cin || (time1 < 0)){ //the # is negative
cout << "Please enter a non-negative number!\n";
cin >> time1;
}
cout << runner2 << "'s finishing time: ";
cin >> time2;
while (!cin || (time2 < 0)){ //the # is negative
cout << "Please enter a non-negative number!\n";
cin >> time2;
}
cout << runner3 << "'s finishing time: ";
cin >> time3;
while (!cin || (time3 < 0)){
cout << "Please enter a non-negative number!\n";
cin >> time3;
}
// This is for Rank1----------------------------
cout << "1st place : ";
if((time1 < time2)&&(time1 < time3))
{
cout << left << setw(5) << runner1 << " " << right
<< setw(5) << time1 << endl;
}
else if (time2 < time3){
cout << left << setw(5) << runner2 << " " << right
<< setw(5) << time2 << endl;
}
else {
cout << left << setw(5) << runner3 << " " << right
<< setw(5) << time3 << endl;
}
//Rank2------------------------------------
cout << "2nd place : ";
if ((time1 < time2)&&(time3 < time1)){
cout << left << setw(5) << runner1 << " " << right
<< setw(5) << time1 << endl;
}
else if ((time3 < time2)&&(time1 < time3)){
cout << left << setw(5) << runner3 << " " << right
<< setw(5) << time3 << endl;
}
else {
cout << left << setw(5) << runner2 << " " << right
<<setw(5) << time2 << endl;
}
// RANK 3-----------------------------------
cout << "3rd place : ";
if ((time1 > time2)&&(time1 > time3)){
cout << left << setw(5) << runner1 << " " << right
<< setw(5) << time1 << endl;
}
else if ((time1 < time3)&&(time3 > time2)){
cout << left << setw(5) << runner3 << " " << right
<< setw(5) << time3 << endl;
}
else {
cout << left << setw(5) << runner2 << " " << right
<<setw(5) << time2 << endl;
}
return 0;
}
This routine will do the validation:
bool validateString(const std::string& s)
{
for (const char c : s) {
if (!isalpha(c) && !isspace(c))
return false;
}
return true;
}
You might want to use something like
#include <cctype>
#include <string>
#include <iostream>
int main()
{
std::string foo;
bool valid;
do {
std::getline(std::cin, foo);
valid = true;
for (std::size_t i{}; i < foo.length() && valid; ++i) {
if (!(std::isalpha(static_cast<unsigned char>(foo[i])) ||
std::isspace(static_cast<unsigned char>(foo[i]))))
valid = false;
}
} while (!valid);
}
which checks every character for being a letter or a space.
Here is my proposal for a solution:
#include <iostream>
#include <string>
bool validateString(std::string toCheck) {
bool correct = false;
for (int i = 0; i<toCheck.length(); i++) {
if ((toCheck[i] >= 65 && toCheck[i] <= 90) || (toCheck[i] >= 97 && toCheck[i] <= 122) || toCheck[i] == 32) {
correct = true;
}
else {
return false;
}
}
return correct;
}
int main()
{
std::cout << validateString("Whats up peeps") << std::endl;
std::cout << validateString("234235") << std::endl;
system("pause");
return 0;
}
Using ASCII Table.
Note: Might not be the best way to do it but it works.

Restricting character input in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm really curious as how to restrict character input in a program like a calculator can anyone teach me how to do it, I'm really new to this. And if someone answers could you please explain every line of code in your answer. Thanks in advance. :)
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int choice;
double add, sub, mul, div, rem, square, power, v1, v2;
long double sine, cosine, tangent;
do{
cout << "Choose an operation." << endl << "\n";
cout << "[1] Addition." << endl;
cout << "[2] Subtraction." << endl;
cout << "[3] Multiplication." << endl;
cout << "[4] Division." << endl;
cout << "[5] Exit." << endl;
cin >> choice;
while (choice < 1 || choice > 5){
cout << "Please Choose from 1 to 5" << endl;
cin >> choice;
}
if (choice == 1){
cout << "Please Enter 1st value: ";
cin >> v1;
cout << "Please Enter 2nd value: ";
cin >> v2;
add = v1 + v2;
cout << "The answer is: " << fixed << setprecision(2) << add << endl << endl;
}
else if (choice == 2){
cout << "Please Enter 1st value: ";
cin >> v1;
cout << "Please Enter 2nd value: ";
cin >> v2;
sub = v1 - v2;
cout << "The answer is: " << fixed << setprecision(2) << sub << endl << endl;
}
if (choice == 3){
cout << "Please Enter 1st value: ";
cin >> v1;
cout << "Please Enter 2nd value: ";
cin >> v2;
mul = v1 * v2;
cout << "The answer is: " << fixed << setprecision(2) << mul << endl << endl;
}
if (choice == 4){
cout << "Please Enter 1st value: ";
cin >> v1;
cout << "Please Enter 2nd value: ";
cin >> v2;
div = v1 / v2;
rem = fmod (v1,v2);
cout << "The answer is: " << fixed << setprecision(2) << div << " remainder " << rem << endl << endl;
}
if (choice == 5)
break;
}
while (choice != 5);
{
cout << endl << "Goodbye.";
}
return 0;
}
Check the documentation of the functions you are using.
Simplified code:
double v1;
std::cin >> v1;
This is attempting to extract a double from std::cin, skipping leading whitespace.
If extraction fails -- e.g. because somebody entered something that isn't a representation of a double value -- a zero is written (since C++11, previously the value was left unchanged), and the failbit set on the stream.
This can be checked, and cleared:
if ( std::cin.fail() )
{
// handle error
std::cin.clear();
}
Actually the page on clear() has a fully functional example of reading a number, checking for failure, and repeating the input.
That being said, I second #Maikel's comment. If you want to take this beyond the experimentation stage, you will want to write a true grammar parser, for which Boost.Spirit is a strong choice.

Splitting lines from an external text file in to a structure?

I really have no idea, how to explain this question. But here it is...
Suppose I have an external text file, and it's content goes like this:
1 Crysis 2012 Crytek Ubisoft
2 FarCry 2009 Crytek Ubisoft
3 Need_For_Speed 1695 EA Ubisoft
4 Assassin'sCreed 2008 Ubisoft Ubisoft
5 COD 2010 Activision Ubisoft
then i've used this code:
if (fout.is_open())
{
std::string delim = " ";
size_t pos = 0;
std::string token;
while (getline(fout, line))
{
while ((pos = line.find(delim)) != std::string::npos)
{
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delim.length());
}
std::cout << line << std::endl;
}
}
this code splits the text lines and outputs the following
1
Crysis
2012
Crytek
Ubisoft
2
FarCry
2009
Crytek
Ubisoft
3
Need_For_Speed
1695
EA
Ubisoft
4
Assassins'sCreed
2008
Ubisoft
Ubisoft
5
COD
2010
Activision
Ubisoft
What I actually want is to create a new structure in each loop and create it's 5 variables to hold each of the porperties for every individual game. For Example
struct Game
{
int id;
string title;
int year;
string developer;
string publisher;
};
Now from the output:
1
Crysis
2012
Crytek
Ubisoft
As the loop runs I want to create a new "Game" Structure and assign these values to it's variables and then push the structure in to a vector.
Here is a summary of what I am trying to create and how far I have come:
The program is a database of games. The user is able to add,delete,search and edit any item from the database. As the program runs and the user adds a Game it successfully gets written in the external .txt file and also get pushed to the end of the vector. Now that is all fine. But when I close the program and run it again, there is data in the text file but the vector is empty. So i want the vector to get populated again with the data in the .txt file, so that the user can continue working with the database.
I dont know if I explained the problem well enough. Or I might have over explained it. I am actually a noob in C++.
Thanks in advance..
here is the full code for the program i am working on...
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Game
{
int id;
int year;
string title;
string publisher;
string developer;
};
void ShowData(vector<Game> myDatabase)
{
cout << endl;
for(size_t i = 0; i <= myDatabase.size()-1; i++)
{
cout << endl;
cout << "-------------------------------------------------------"<<endl;
cout << " ITEM NO" << " " << i + 1 << " " <<endl;
cout << "-------------------------------------------------------"<<endl;
cout << " TITLE: " << myDatabase[i].title << endl;
cout << " YEAR: " << myDatabase[i].year << endl;
cout << "DEVELOPER: " << myDatabase[i].developer << endl;
cout << "PUBLISHER: " << myDatabase[i].publisher << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string option;
int serialNumber = 0;
int count = 0;
string line;
vector<Game> Database;
fstream fout;
fout.open("Database.txt");
if (fout.is_open())
{
std::string delim = " ";
size_t pos = 0;
std::string token;
while (getline(fout, line))
{
Game newGame;
std::cout << line << std::endl;
}
while (getline(fout, line))
{
while ((pos = line.find(delim)) != std::string::npos)
{
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delim.length());
}
std::cout << line << std::endl;
}
}
else
{
cout << "There was an error opening the file.";
}
cout << endl;
repeat:
cout << endl;
cout << "ADD | SHOW | DELETE | EDIT | SEARCH " << endl;
cout << "SAY : ";
cin >> option;
if(option == "ADD" || option == "Add" || option == "add")
{
serialNumber += 1;
Game NewGame;
NewGame.id = serialNumber;
cout << endl << "Name: ";
cin >> NewGame.title;
cout << "Year: ";
cin >> NewGame.year;
cout << "Developer: ";
cin >> NewGame.developer;
cout << "Publisher: ";
cin >> NewGame.publisher;
cout << endl;
Database.push_back(NewGame);
cout << endl;
cout << "Size is: " << Database.size();
fout << serialNumber << " " << Database[Database.size() - 1].title << " " << Database[Database.size() - 1].year << " "<< Database[Database.size() - 1].developer << " " << Database[Database.size() - 1].publisher << endl;
goto repeat;
}
if (option == "SHOW" || option == "Show" || option == "show")
{
ShowData(Database);
goto repeat;
}
if(option == "DELETE" || option == "Delete" || option == "delete")
{
int choose;
cout << "Delete Item No: ";
cin >> choose;
Database.erase(Database.begin() + (choose - 1));
cout << endl;
ShowData(Database);
goto repeat;
}
if(option == "SEARCH" || option == "Search" || option == "search")
{
cout << "Search By [ID, TITLE, YEAR, DEVELOPER, PUBLISHER] : ";
string choose;
cin >> choose;
if(choose == "ID" || choose == "Id" || choose == "id")
{
int idNumber;
cout << "ID No: ";
cin >> idNumber;
cout << endl;
cout << "ITEM NO" << "[" << idNumber << "]" <<endl;
cout << " TITLE: " << Database[idNumber - 1].title << endl;
cout << " YEAR: " << Database[idNumber - 1].year << endl;
cout << "DEVELOPER: " << Database[idNumber - 1].developer << endl;
cout << "PUBLISHER: " << Database[idNumber - 1].publisher << endl;
goto repeat;
}
else if (choose == "TITLE" || choose == "Title" || choose == "title")
{
string whatTitle;
cout << "Enter Title: ";
cin >> whatTitle;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].title == whatTitle)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "YEAR" || choose == "Year" || choose == "year")
{
int whatYear;
cout << "Enter Year: ";
cin >> whatYear;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].year == whatYear)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "DEVELOPER" || choose == "Developer" || choose == "developer")
{
string whatDeveloper;
cout << "Enter Developer Name: ";
cin >> whatDeveloper;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].developer == whatDeveloper)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "PUBLISHER" || choose == "Publisher" || choose == "publisher")
{
string whatPublisher;
cout << "Enter Publisher Name: ";
cin >> whatPublisher;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].publisher == whatPublisher)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
}
if (option == "EDIT" || option == "Edit" || option == "edit")
{
int whichItem;
cout << "Enter Item No: ";
cin >> whichItem;
cout << endl << "Name: ";
string name;
cin >> name;
Database[whichItem - 1].title = name;
cout << "Year: ";
int year;
cin >> year;
Database[whichItem - 1].year = year;
cout << "Developer: ";
string developer;
cin >> developer;
Database[whichItem - 1].developer = developer;
cout << "Publisher: ";
string publisher;
cin >> publisher;
Database[whichItem - 1].publisher = publisher;
cout << endl;
ShowData(Database);
goto repeat;
}
fout.close();
system("PAUSE");
return 0;
}
You can create a struct as shown here.
In the example, they have an array of structs. In order to access an element of the struct use the . operator.
In C++11, you can use a tuple, instead of a struct.
Tuple vs Struct - Stackoverflow.
The idea is that the first can provide more generic operations, while the second has far better readability and you do not have to remember the order of your data members, IMHO.
[EDIT]
AS R. Hasan states, the question is a duplicate of this question.
I am not sure that's what you are looking for, but consider this (and don't forget to include vector)
First, we define custom structure
struct Game //your structure
{
int id;
std::string title;
int year;
std::string developer;
std::string publisher;
};
Now we overload operator>> (it's similar to using cin >> someVariable). Fstream already has methods to write in variables of standard types.
bool operator>>(std::fstream& fs, Game& g)
{
if (fs >> g.id >> g.title >> g.year >> g.developer >> g.publisher)
return true;
return false;
}
/*
fs >> g.id >> g.title equals (fs.operator>>(g.id)).operator>>(g.title) ...
*/
Standard operator>> returns reference to fstream, so we are able to write everything in just 1 line of code. If writing does fail (e.g. end of file reached) we return false.
std::vector<Game> vec;
STL vector
- standard container, that contains your Game structs
if (fout.is_open())
{
for ( ; ; )
{
Game g; //creating instantiation of your struct Game
if (fout >> g) //reading from your file
vec.push_back(g); //1 of STL vector methods, check link to cppreference higher
else //if reading fails, we break our infinite loop
break;
}
}
for (auto x : vec) //going through every element of our vector.
cout << x.id << " "; //and printing first variable of your structure

C++ Constant char

I built a simple calculator out of c++, it uses chars, so (+,-*,/) will works as math operators but when a user inputs an '=' it does't work.
#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
using namespace std;
#define PI 3.14159265359
#define NEWLINE '\n'
void printf(string string)
{
cout << string;
}
int main ()
{
char operation;
double a,b,c, value;
double answer = 0;
bool more = true;
cout << "Welcome to My Calculator\n\nInput a value: ";
cin >> answer;
operations:
cin >> operation;
if (operation != '=') {
if (operation == '+') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer += value;
cout << "Equals " << answer << "\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '-') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer -= value;
cout << "Equals " << answer << "\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '*') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer *= value;
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '/') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer /= value;
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '^') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer = pow(answer, value);
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '=') {
cout << "\nFinal Answer = " << answer << "\n\nNew operation [yes/no]: ";
string check;
cin >> check;
if (check == "yes") {
cout << "\nInput value: ";
cin >> answer;
cout << "\n";
goto operations;
} else {
cout << "\nGoodbye for now...\n";
return 0;
}
}
} else {
cout << "Unknown Error! Program Closing...";
return 0;
}
return 0;
}
When a user uses any operation besides = it works perfectly, but if I use and equals sign it doesn't work.
Example program out put:
Welcome to My Calculator
Input a value: 4
+4
4 + 4
Equals 8
8 - New Operation? - 3
8 - 3
Equals 5
5 - New Operation? * 5
5 * 5
Equals 25
25 - New Operation? /2
25 / 2
Equals 12.5
12.5 - New Operation? ^2
12.5 ^ 2
Equals 156.25
156.25 - New Operation? =
Unknown Error! Program Closing...
if (operation != '=') {
...
if (operation == '=') {
}
}
If operation isn't equal to "=" and if it's equal to "=". I think you planned to put a closure operator or something like that in the first outer if.
your statement if (operation != '=') causes the control to be transferred to the else statement
Because you have an if (operation != '=') outside the if checking for =. You don't want to do that.