I'm trying to learn C++ and i cant figure a problem out.
My code:
#include <iostream>
using namespace std;
int userContinue = true;
int userContinueString;
int getUserInput() {
int userInput1;
int userInput2;
cout << "Please enter your first number: ";
cin >> userInput1;
cout << endl << "Please enter your second number: ";
cin >> userInput2;
cout << endl << "The result of the two numbers together: " << userInput1+userInput2;
userInput1 = 0;
userInput2 = 0;
return 0;
}
int main()
{
while (userContinue == true) {
getUserInput();
cout << endl << "Would you like to continue? (Y/N): ";
cin >> userContinueString;
if (userContinueString ='Y') {
}
else {
userContinue = false;
}
}
return 0;
}
The code works fine until i input "Y" ant then it keeps looping as shown here: Video
First, make sure you compile your code with some warning switches such as -Wall -Wpedantic. These switches will help you. For instance, in your original code, my compiler prints the following warnings:
prog.cpp:25:28: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if (userContinueString = 'Y') {
~~~~~~~~~~~~~~~~~~~^~~~~
prog.cpp:25:28: note: place parentheses around the assignment to silence this warning
if (userContinueString = 'Y') {
^
( )
prog.cpp:25:28: note: use '==' to turn this assignment into an equality comparison
if (userContinueString = 'Y') {
^
==
1 warning generated.
Then, I fix the corresponding line with ==, which was already suggested in the comments. Then, your comparison should be case-insensitive. Finally, you would like to compare character objects with respect to 'y' or 'Y':
#include <cctype>
#include <iostream>
using namespace std;
int userContinue = true;
char /* not int */ userContinueString;
int getUserInput() {
int userInput1;
int userInput2;
cout << "Please enter your first number: ";
cin >> userInput1;
cout << endl << "Please enter your second number: ";
cin >> userInput2;
cout << endl
<< "The result of the two numbers together: " << userInput1 + userInput2;
userInput1 = 0;
userInput2 = 0;
return 0;
}
int main() {
while (userContinue == true) {
getUserInput();
cout << endl << "Would you like to continue? (Y/N): ";
cin >> userContinueString;
if (std::tolower(userContinueString) == 'y') {
} else {
userContinue = false;
}
}
return 0;
}
EDIT. I have improved the answer by taking into account David's comment below. Note the use of #include <cctype> and std::tolower.
EDIT. I have tried improving the answer further by trying to address the "learning C++" comment below:
#include <functional>
#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>
template <class value_t,
typename std::enable_if<std::is_floating_point<value_t>::value,
int>::type = 0>
struct Calculator {
Calculator() = default;
explicit operator bool() {
while (true) {
std::cout << "Valid operations: +, -, *, /, 0 (exit)\n";
std::cout << "What would you like to do: ";
if (!getUserInput(operation)) {
std::cerr << "Wrong input for operation\n";
continue;
}
switch (operation) {
case '0':
return false;
case '+':
case '-':
case '*':
case '/':
break;
default:
std::cerr << "Wrong input for operation\n";
continue;
}
std::cout << "Please enter v1: ";
if (!getUserInput(v1)) {
std::cerr << "Wrong input for v1\n";
continue;
}
std::cout << "Please enter v2: ";
if (!getUserInput(v2)) {
std::cerr << "Wrong input for v2\n";
continue;
}
calculate();
return true;
}
}
friend std::ostream &operator<<(std::ostream &os, const Calculator &c) {
os << "v1 " << c.operation << " v2 = " << c.result;
return os;
}
private:
char operation;
value_t v1, v2, result;
std::string line;
void calculate() {
switch (operation) {
case '+':
return calculate(std::plus<value_t>{});
case '-':
return calculate(std::minus<value_t>{});
case '*':
return calculate(std::multiplies<value_t>{});
case '/':
return calculate(std::divides<value_t>{});
case '0':
return;
}
}
template <class Func> void calculate(Func &&f) { result = f(v1, v2); }
template <class T> bool getUserInput(T &t) {
std::cin >> line;
std::istringstream ss{line};
return (ss >> t) && (ss >> std::ws).eof();
}
};
int main() {
Calculator<double> c;
while (c)
std::cout << c << '\n';
return 0;
}
Related
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 2 years ago.
Improve this question
I need some help about class functions because whatever i tried gave me errors. I tried to create pointers which holds my main variables but still couldn't figure out even i read a lot of topics and watched videos about them. I have something wrong with my logic but can not find that actually. After i get my arrays i want to use them in class part. For example when i switch case to 0 i want to show all contacts. For that i have to carry my arrays into the class but i couldn't. I will use them for editing, adding persons or deleting them. So i need my counters too. As i said. If there is a way can someone please at least give an example for me? Thanks a lot.
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void printline(char, int);
class person{
private:
int order;
string name;
string surname;
string phonenumber;
public:
void setName(string isim){
name=isim;
}
string getName(){
return name;
}
void setSurname(string soyad){
surname=soyad;
}
string getSurname(){
return surname;
}
void setPhonenumber(string numara){
phonenumber=numara;
}
string getPhonenumber(){
return phonenumber;
}
};
int main() {
person kisi;
FILE* myFile;
int i = 0;
int j = 0;
int k = 0;
int choice;
int mOrder;
char* mName[20],mSurname[20],mPhone[20];
myFile = fopen("phoneData.txt", "r");
if (myFile != NULL)
while (fscanf(myFile, "%d%s%s%s", &mOrder, mName, mSurname, mPhone) != EOF)
i++;
fclose(myFile);
// this is where we find i and now i can create my arrays.
int *orderArray;
char *nameArray[i];
char *SurnameArray[i];
char *PhoneArray[i];
orderArray = (int *) malloc(i * sizeof(int));
for (int n=0;n<i;n++)
{
nameArray[n] = (char*) malloc(20 * sizeof(char));
SurnameArray[n] = (char *) malloc(20 * sizeof(char));
PhoneArray[n] = (char *) malloc(20 * sizeof(char));
}
myFile = fopen("phoneData.txt", "r");
if (myFile == NULL)
{
printf("There is no file.\n");
}
else
{
int m=0;
while (fscanf(myFile, "%d%s%s%s", &orderArray[m], nameArray[m], SurnameArray[m], PhoneArray[m]) != EOF){
m++; //this is the part where we read the txt file correctly and seperate it into the parts.
}
fclose(myFile);
//i made this part just to see if my arrays work or not. They worked.
/*
for (int j=0;j<i;j++)
{
cout<<orderArray[j]<<" "<<nameArray[j]<<" " << SurnameArray[j]<<" "<<PhoneArray[j]<<endl;
}
*/
}
// menü burası olacak
/*
cout << "--- Welcome to the PhoneBook ---" << endl;
printline('-', 32);
cout << "0. Show all the contacts on PhoneBook" << endl;
cout << "1. Add a contact to PhoneBook" << endl;
cout << "2. Search a contact on PhoneBook" << endl;
cout << "3. Edit a contact on PhoneBook" << endl;
cout << "4. Delete a contact from PhoneBook\n" << endl;
cout << "Please make a choice: " << endl;
cin >> choice;
*/
//switch cases will be there.
/*
switch(choice){
case 0:
showContacts();
break;
case 1:
addContacts();
break;
case 2:
searchContacts();
break;
case 3:
editContacts();
break;
case 4:
deleteContacts();
break;
}
*/
return 0;
}
void printline(char ch, int size)
{
for(int i=0; i<size; i++)
cout << ch;
cout << "\n";
}
Please take this as one example of possible millions of other solutions.
I will edit the answer later and put explanations and comments. Now I nned to do other stuff
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
struct Person {
unsigned int index{};
std::string name{};
std::string surname{};
std::string phoneNumber{};
friend std::istream& operator >> (std::istream& is, Person& p) {
if (std::string line{}; std::getline(is, line)) {
std::istringstream iss{ line };
iss >> p.index >> p.name >> p.surname >> p.phoneNumber;
}
return is;
}
friend std::ostream& operator << (std::ostream& os, const Person& p) {
return os << p.index << '\t' << p.name << '\t' << p.surname << '\t' << p.phoneNumber;
}
};
struct PhoneBook {
std::vector<Person> persons{};
friend std::istream& operator >> (std::istream& is, PhoneBook& p) {
p.persons.clear();
std::copy(std::istream_iterator<Person>(is), {}, std::back_inserter(p.persons));
return is;
}
friend std::ostream& operator << (std::ostream& os, const PhoneBook& p) {
std::copy(p.persons.begin(), p.persons.end(), std::ostream_iterator<Person>(os, "\n"));
return os;
}
};
struct PhoneBookAdministration {
PhoneBook phoneBook{};
std::string phoneBookFileName{};
void load(const std::string& fileName) {
phoneBookFileName = fileName;
if (std::ifstream phoneBookFileStream(fileName); phoneBookFileStream)
phoneBookFileStream >> phoneBook;
else std::cerr << "\nError: Could not open " << fileName << "\n\n";
}
void saveAs() {
std::cout << "\n\nSave As\n\nPlease enter a filename:\n";
if (std::string fileName{}; std::cin >> fileName) {
phoneBookFileName = fileName;
save();
}
}
void save() const {
if (std::ofstream phoneBookFileStream(phoneBookFileName); phoneBookFileStream) {
phoneBookFileStream << phoneBook;
}
else std::cerr << "\nError: Could not open " << phoneBookFileName << "\n\n";
}
void show() const {
std::cout << "\n\nContents of phone book:\n" << phoneBook << "\n\n";
}
void addEntry() {
std::cout << "\n\nAdd entry to phone book\nEnter name, surname and phone number:\n";
if (std::string n{}, s{}, p{}; std::cin >> n >> s >> p)
phoneBook.persons.emplace_back(phoneBook.persons.size(), n, s, p);
}
void searchContact() const {
std::cout << "\n\nSearch entry in phone book\nEnter name to search for:\n";
if (std::string n{}; std::cin >> n) {
if (auto pos = std::find_if(phoneBook.persons.begin(), phoneBook.persons.end(), [&n](const Person& p) {return p.name == n; }); pos != phoneBook.persons.end())
std::cout << "\n\nPerson '" << n << "' found:\n" << *pos << '\n';
else std::cout << "\n\nPerson '" << n << "' not found\n";
}
}
void editContact() {
std::cout << "\n\nEdit contact. Here is the phone book\n" << phoneBook << "\n\nPlease enter the index of an entry:\n";
if (size_t index{}; std::cin >> index && index < phoneBook.persons.size()) {
std::cout << "\n\nEnter name, surname and phone number:\n";
if (std::string n{}, s{}, p{}; std::cin >> n >> s >> p)
phoneBook.persons[index] = { phoneBook.persons[index].index, n, s, p };
}
else std::cout << "\n\nError, problem with given index\n";
}
void deleteContact() {
std::cout << "\n\nDelete contact. Here is the phone book\n" << phoneBook << "\n\nPlease enter the index of an entry:\n";
if (size_t index{}; std::cin >> index && index < phoneBook.persons.size())
phoneBook.persons.erase(phoneBook.persons.begin() + index);
}
};
int main() {
PhoneBookAdministration pba{};
pba.load("r:\\pb.txt");
bool runProgram{ true };
while (runProgram) {
// Show menu
std::cout <<
"\n\n\nMain Menu\n"
"You have the follwing options:\n"
" 1 - Save\n"
" 2 - Save as\n"
" 3 - Show\n"
" 4 - Add Entry\n"
" 5 - Search\n"
" 6 - Edit entry\n"
" 7 - Delete entry\n"
" 0 - Exit program\n\n"
"Please select:\n";
if (int selection{}; std::cin >> selection) {
switch (selection) {
case 1:
pba.save();
break;
case 2:
pba.saveAs();
break;
case 3:
pba.show();
break;
case 4:
pba.addEntry();
break;
case 5:
pba.searchContact();
break;
case 6:
pba.editContact();
break;
case 7:
pba.deleteContact();
break;
case 0:
std::cout << "\n\nExiting . . .\n\n";
runProgram = false;
break;
default:
std::cout << "\n\nWrong selection. Please try again\n";
break;
}
}
else std::cerr << "\n\nError: Problem with selection\n";
}
return 0;
}
I am a new contributor and here I am trying to make a simple calculator but having errors in my code. When I compile the code I get:
Error: C:\Users\IJLAL\Documents\collect2.exe [Error] ld returned 1 exit status while compiling
In case it could help, here is the screen shot of error when I pressed compile button or F11 in Dev C++:
Here is my code:
#include<iostream>
using namespace std;
void fun(float a, float b);
int main()
{
float a, b, sum, sub, mul, divide, mod;
char op;
//operands and operators are enterd by the user
cout<<"Enter any two operands with operator=";
cin>>a>>op>>b;
fun(a, b);
return 0;
}
void op(float a, float b)
{
if(a+b)
{
float sum=a+b;
cout<<"\nAddition of two numbers is="<<sum;
}
else if(a-b)
{
float sub=a-b;
cout<<"\nSubtraction of two numbers is="<<sub;
}
else if(a*b)
{
float mul=a*b;
cout<<"\nMultiplication of two numbers is="<<mul;
}
else if(a/b)
{
float divide=a/b;
cout<<"\nDivision of two number is="<<divide;
}
else
{
cout<<"\nInvalid operator.......";
}
}
Please tell me the solution of this problem, so that I can compile the code successfully. If there is any better solution to make a simple calculator on beginner level please mention it in answer.
You're not so far from a result. The problem is that you have not defined the function fun(). Furthermore, in the function op() that you have defined, you do not use the operator of the input.
So first thing to do is to change the signature of the function:
void fun(char op, float a, float b);
Then you need to invoke your function in main(), passing also the operation that was requested by the user:
fun(op, a, b);
Finally you need to change all your if to check if op is the matching operator:
void fun(char op, float a, float b)
{
if(op=='+')
{
...
}
else if(op=='-')
{
...
You should then get the expected result.
Online demo
Aditional infos
if (a+b) just calculates the expression using the two values of the user, and if it's non zero, it's considered as true.
once you got this program to work, you can look for the switch statement
You can use additional functions to make a better calculator. You can use this code. Hope this code will be helpful for you.
The header <iomanip> is part of the Input/output library of the C++ Standard Library and <math.h> is used when we perform mathematical operations.
#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
char op;
using namespace std;
void sum()
{
int sum = 0;
int n;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout<< "Enter number "<<i<<":\n\n" ;
cin>>n;
sum+=n;
}
cout<<"sum is: "<< sum<<endl<<endl;
}
void diff()
{
int diff;
int n1,n2;
cout<<"enter two numbers to find their difference:\n\n";
cout<<"enter first number:";
cin>>n1;
cout<<"\nenter second number:";
cin>>n2;
diff=n1-n2;
cout<<"\ndifference is:"<<diff<<endl<<endl;
}
void pro()
{
int pro=1;
int n;
int numberitems;
cout<<"enter number of items:\n";
cin>>numberitems;
for(int i=0;i<=numberitems;i++)
{
cout<<"\nenter item "<<i<<":";
cin>>n;
pro*=n;
}
cout<<"product is:"<<pro<<endl<<endl;
}
void div()
{
int div;
int n1;
int n2;
cout<<"enter 2 numbers to find their quotient\n\n";
cout<<"enter numerator:";
cin>>n1;
cout<<"\nenter denominator:";
cin>>n2;
div=n1/n2;
cout<<"\nquotient is:"<<div<<endl<<endl;
}
void power()
{
long int p;
int res=1,n;
cout<<"enter number:";
cin>>n;
cout<<"\nenter power:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=n*res;
}
cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
}
void sq()
{
float s;
int n;
cout<<"enter number to find its square root:";
cin>>n;
s=sqrt(n);
cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
}
void fact()
{
long int f=1;
int c=1,n;
cout<<"enter number to find its factorial:";
cin>>n;
while(c<=n)
{
f=f*c;
c+=1;
}
cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;
}
void expo()
{
long double res=1,p;
double e=2.718281828;
cout<<"enter power of exponential function:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=e*res;
}
cout<<" e^ "<<p<<" is :"<<res<<endl;
}
int main()
{
system("cls");
do
{
system("pause");
system("cls");
cout<<"***which operation you want to perform***\n";
cout<<"press 0 for exit\n";
cout<<"press 1 for addition \n";
cout<<"press 2 for subtraction\n";
cout<<"press 3 for multiplication\n";
cout<<"press 4 for division\n";
cout<<"press 5 for power calculation\n";
cout<<"press 6 for square root \n";
cout<<"press 7 for factorial calculation\n";
cout<<"press 8 for exponential calculation\n";
cout<<"press option:";
cin>>op;
switch(op)
{
case '1':
sum();
break;
case '2':
diff();
break;
case '3':
pro();
break;
case '4':
div();
break;
case '5':
power();
break;
case '6':
sq();
break;
case '7':
fact();
break;
case '8':
expo();
break;
case '0':
exit(0);
default:
cout<<"invalid input" ;
system("cls");
}
}
while(op!='0');
getch();
}
Hey I'm still a newbie on c++ but hope this would help, I used while loop to loop the calculator but I don't have a good error handler for example when users try to input a letter instead of numbers.
#include <iostream>
#include <cmath>
using namespace std;
int result (int a, int b, char op);
int main()
{
char optr, choice;
int nr1, nr2;
while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;
result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;
if (choice =='N'||choice =='n'){
break;
}
}
}
int result (int a, int b, char op)
{
int result;
if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated." << endl;
// i still dont know how to properly use error handling
}
}
I won't criticize your solution as I have a better solution as you mentioned "please mention a better solution in answer"
Here's my solution with comments to make you understand what each statement does.
#include <iostream>
using namespace std;
// I am going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
cout << "Enter a number: ";
int no{};
cin >> no;
return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
cout << "Enter opperator: ";
char opr{};
cin >> opr;
return opr;
}
int calculate(int input1, char opper, int input2)
{
if (opper == '+')
{
return input1 + input2;
}
else if (opper == '-')
{
return input1 - input2;
}
else if (opper == '*')
{
return input1 * input2;
}
else if (opper == '/')
{
return input1 / input2;
}
return 0;
}
int main()
{
// get the first no. from user
// getUserInput();
// get the math oppperator from the user
// getMathOpperator();
// get the second no. from the user
// getUserInput();
// calculate the values
// calculateResults();
// print out the results
// printResults();
cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
while (true)
{
int input1{ userInput() };
int input2{ userInput() };
char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
}
return 0;
}
Just copy this code and modify however you want to.
#include <iostream>
int main() {
int math_ques_1, math_ques_2;
std::cout << "What is the base of the question?" << std::endl;
std::cin >> math_ques_1;
std::cout << "What do you want to add to the base?" << std::endl;
std::cin >> math_ques_2;
std::cout << "The answer is " << math_ques_1 + math_ques_2 << "." << std::endl; }
In my class one of our assignments is to convert a prefix equation to infix. After reading that section I still have no idea what I'm doing. The book had some code that will solve a prefix equation when given but I have no idea how it does it or how I would display the infix version. Any help would be appreciated in explaining how this code finds the solution and how I could have it display a infix version.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
int prefixExpr(istream &exprStream);
int main() {
string input;
cout << "Enter prefix expressions to evaluate. \nPress enter after each expression, and press enter on a blank line to quit." << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
while (input.size() != 0){
istringstream exprStream(input);
cout << prefixExpr(exprStream) << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
}
return 0;
}
int prefixExpr(istream &exprStream) {
char ch = exprStream.peek();
while (isspace(ch)) {
ch = exprStream.get();
ch = exprStream.peek();
}
cout << ch << endl;
if (isdigit(ch)) {
int number;
exprStream >> number;
cout << number << endl;
return number;
}
else {
ch = exprStream.get();
int value1 = prefixExpr(exprStream);
int value2 = prefixExpr(exprStream);
switch (ch) {
case '+': return value1 + value2;
case '-': return value1 - value2;
case '*': return value1 * value2;
case '/': return value1 / value2;
default: cout << "Bad input expression";
exit(1);
}
}
}
I'm figuring out how to loop my code and now it got me confused, any help would be much appreciated, im a beginner here so please don't scold me.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char ans;
cout << "CONVERSION\n\n";
cout << "Base 11 to Decimal\n";
a:cout << "Base 11: ";
getline(std::cin, str);
const auto bad_loc = str.find_first_not_of("0123456789aA");
if (bad_loc != std::string::npos)
{
std::cerr << "Invalid Input\n";
goto a;
}
unsigned long ul = std::stoul(str, nullptr, 11);
cout << "Decimal: " << ul << "\n\n";
cout << "Do you want to continue (Y/N)? ";
cin >> ans;
if (ans == 'y')
{
goto a;
}
else if (ans == 'n')
{
cout <<"Name:\tXXXXXXXX\n";
cout <<"Course:\tXXXXXXXX";
cout <<"Section:\tXXXXXXXX\n";
cout <<"Schedule:\tXXXXXXXX\n";
cout <<"Professor:\tXXXXXXXX\n";
}
return 0;
}
the output should be like this
CONVERSION
Base 11 to Decimal
Base 11: B
Invalid Input!
Base 11: A
//blank
Do you want to continue (Y/N)? X
Invalid Answer! (Y/N)? Y
//blank
Base11:
My problems are
(1)The program stops after looping in "base11:" whenever i answer Y and (2)if I answer any letter from "Do you want..." the program will end. (3) How to fix this thing.
We beginners should help each other should not we?:)
The program can look something like the following
#include <iostream>
#include <string>
#include <limits>
int main()
{
std::cout << "CONVERSION\n\n";
std::cout << "Base 11 to Decimal\n";
char ans;
do
{
std::string s;
bool valid_input = false;
while ( !valid_input )
{
std::cout << "Base 11: ";
if ( !std::getline( std::cin, s ) ) break;
if ( !( valid_input = s.find_first_not_of( "0123456789aA" ) == std::string::npos ) )
{
std::cout << "Invalid Input\n\n";
}
}
if ( !valid_input )
{
std::cout << "See you later!" << std::endl;
break;
}
unsigned long value = std::stoul( s, nullptr, 11 );
std::cout << "Decimal: " << value << "\n\n";
std::cout << "Do you want to continue (Y/N)? ";
std::cin >> ans;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
} while ( ans == 'y' || ans == 'Y' );
std::cout <<"Name:\tXXXXXXXX\n";
std::cout <<"Course:\tXXXXXXXX";
std::cout <<"Section:\tXXXXXXXX\n";
std::cout <<"Schedule:\tXXXXXXXX\n";
std::cout <<"Professor:\tXXXXXXXX\n";
return 0;
}
If the input looks like
B
A
Y
C
AA
N
then the output will be
CONVERSION
Base 11 to Decimal
Base 11: B
Invalid Input
Base 11: A
Decimal: 10
Do you want to continue (Y/N)? Y
Base 11: C
Invalid Input
Base 11: AA
Decimal: 120
Do you want to continue (Y/N)? N
Name: XXXXXXXX
Course: XXXXXXXXSection: XXXXXXXX
Schedule: XXXXXXXX
Professor: XXXXXXXX
Pay attention to statement
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
that skips the new line character entered after inputting ans using operator >>.
bool run_attempt() {
get some input
if (bad input)
return false;
else {
do something good with the input
return true;
}
}
void main() {
bool success = false;
while (!success) {
success = run_attempt();
}
}
For some reason my bank script isn't working. More specifically, the search() does not work. I kind of understand why it doesn't, probably because of if(obj.returnId() == n), but I have no clue how to fix it. When I search an account, it will only allow me to find the last account made, not any of the previous ones. Here is my code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
#include <Windows.h>
#include <conio.h>
using namespace std;
bool loop = true;
class account
{
int id;
char name[40];
char password[40];
public:
void getData()
{
cout << "\nEnter your name: ";
cin >> name;
cout << "\nEnter ID: ";
cin >> id;
cout << "\Enter pass: ";
cin >> password;
}
void showData()
{
cout << "\nName: ";
puts(name);
cout << "\nID: " << id;
cout << "\n";
}
int returnId()
{
return id;
}
};
void createAccount()
{
account obj;
ofstream fileCreate;
fileCreate.open("accounts.dat", ios::binary|ios::app);
obj.getData();
fileCreate.write((char*)&obj,sizeof(obj));
fileCreate.close();
}
void display()
{
account obj;
ifstream fileRead;
fileRead.open("accounts.dat", ios::binary);
while(fileRead.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}
fileRead.close();
}
void search(int n)
{
account obj;
ifstream fileRead;
fileRead.open("accounts.dat", ios::binary);
while(fileRead.read((char *) &obj, sizeof(obj)) );
{
fileRead.seekg(0,ios::beg);
if(obj.returnId() == n)
{
obj.showData();
}
else {
cout << "\nUser not foud!\n";
}
}
fileRead.close();
}
void main()
{
cout << "Welcome to the Bank.\n\n";
while (loop==true)
{
char choice[10];
cout << "Please select an option:\n";
cout << "------------------------------------------------\n";
cout << "(a)Log into an account\n(b)Create an account\n(s)Search an account\n(e)Exit\n";
cout << "------------------------------------------------\n";
cout << "Choice: ";
cin >> choice;
choice[0] = tolower(choice[0]);
cout << "\n------------------------------------------------\n\n";
switch (choice[0])
{
case 'a':
display();
break;
case 's':
int n;
cout << "Enter the ID of the account: ";
cin >> n;
search(n);
break;
case 'b':
createAccount();
break;
case 'e':
loop = false;
break;
default:
system("CLS");
cout << "The option \"" << choice[0] << "\" is invalid.\n\n\n\n";
break;
}
};
cout << "\n\n\n";
cout << "Click anything to exit.";
getch();
}
Your problem is the semicolon at the end of this line:
while(fileRead.read((char *) &obj, sizeof(obj)) );
That makes this loop have an empty body. So you basically read the whole file and throw away the results, except for the last entry.
get rid of this also:
fileRead.seekg(0,ios::beg);
I don't know why you need that, it would only make you read the first entry over and over.
The other error is that you should only say 'User not found' when you've tested all the accounts and they all failed. Your loop (when you've removed the semi-colon) is saying 'User not found' after every failed test.
You probably don't find the entry you are looking for because each time you have read an entry from the file, you reset the position to the beginning. This means that your loop will run forever, reading the same entry over and over again and never finding the entry you search for.
the seek might be the problem:
while(fileRead.read((char *) &obj, sizeof(obj)) ) //;
{
// seek to start?
//fileRead.seekg(0,ios::beg);
...
}
have a look at http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/index.html
aside, use
cout << "text" << endl;
for platform-agnostic newlines.