#include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
string userMiles;
string userSteps;
//declaring constant for number of steps/mile
const int stepsPerMile = 2000;
//getting user's name
cout << "What is the user's name?";
cin >> userName;
cout << endl;
//getting miles walked
cout << "How many miles did " << userName << " hike today?";
cin >> userMiles;
cout << endl;
//getting other steps taken
cout << "How many other steps did " << userName << " take today?";
cin >> userSteps;
cout << endl;
string stepsTakenFromMiles;
string totalSteps;
stepsTakenFromMiles = userMiles * stepsPerMile;
totalSteps = stepsTakenFromMiles + userSteps;
cout << userName << " took " << totalSteps << " steps throughout the day." << endl;
return 0;
}
I am trying to multiply userMiles (string) by stepsPerMile (const int) and I keep getting an error that they are not matching operand types. I have to use stepsPerMile as a const int and cannot change it. How do I change my code to allow both of these inputs to be multiplied?
Read in userMiles and userSteps as integers, not as strings. operator>> can read in many different types, not just std::string. Try using int instead, to match your stepsPerMile constant, eg:
#include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
int userMiles;
int userSteps;
//declaring constant for number of steps/mile
const int stepsPerMile = 2000;
//getting user's name
cout << "What is the user's name?";
cin >> userName;
cout << endl;
//getting miles walked
cout << "How many miles did " << userName << " hike today?";
cin >> userMiles;
cout << endl;
//getting other steps taken
cout << "How many other steps did " << userName << " take today?";
cin >> userSteps;
cout << endl;
int stepsTakenFromMiles;
int totalSteps;
stepsTakenFromMiles = userMiles * stepsPerMile;
totalSteps = stepsTakenFromMiles + userSteps;
cout << userName << " took " << totalSteps << " steps throughout the day." << endl;
return 0;
}
Demo
a nice program I checked it out. Cool program, I like it. I think to solve this problem. Instead of making userMiles a string, make it an int like this
#include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
int userMiles;
string userSteps;
//declaring constant for number of steps/mile
const int stepsPerMile = 2000;
//getting user's name
cout << "What is the user's name?";
cin >> userName;
cout << endl;
//getting miles walked
cout << "How many miles did " << userName << " hike today?";
cin >> userMiles;
cout << endl;
//getting other steps taken
cout << "How many other steps did " << userName << " take today?";
cin >> userSteps;
cout << endl;
string stepsTakenFromMiles;
string totalSteps;
stepsTakenFromMiles = userMiles * stepsPerMile;
totalSteps = stepsTakenFromMiles + userSteps;
cout << userName << " took " << totalSteps << " steps throughout the day." << endl;
return 0;
}
Just change your identifiers
int userMiles, userMiles;
because in C++ you can't use the multiplication operator with strings, this can be actually used in other programming languages such as python like when you multiply a string by a number the string will be repeated but in C++ you can't use arithmetic operators with string except "+" which can be used to join 2 or more strings.
This is a c++ course for beginners check it hope it helps
Related
In my program, I'm having an issue with one function trying to put three different types into an array. Is that possible, or do I have to work around this? I need them in one vector so I can recall that array in another function to delete it.
void addStudent()
{
string major;
double gpa;
unsigned seed = time(0);
srand(seed);
int rand_ID = rand() % 9000 + 1000;
cout << "Please enter major" << endl;
cin >> major;
cout << "Please enter GPA" << endl;
cin >> gpa;
cout << "------Add Student------" << endl;
cout << "ID: " << rand_ID << endl;
cout << "Major: " << major << endl;
cout << "GPA: " << gpa << endl;
ofstream students;
students.open("students.txt", ios_base::app);
students << rand_ID << " " << major << " " << gpa << endl; // I want to turn this into an array that I can send to the file students
}
It sounds like you want to put different students in a vector; and those students will be represented by a struct containing an int ID, string major and double GPA.
struct Student {
int id;
std::string major;
double gpa;
};
std::vector<Student> students;
Okay, so I am writing a C++ program to declare a struct data type that holds the following information on an employee (First Name, Last Name, ID, Pay Rate, and Hours). My problem is that the user can only enter in the ID and First Name, then the whole program runs without letting the user enter the rest of the data.
Heres my code:
#include <iostream>
#include <iomanip>
using namespace std;
struct Employee
{
int employeeID;
char firstName;
char lastName;
float payRate;
int hours;
};
int main()
{
int i, j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
Employee info;
for (i = 0; i < j; i++)
{
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info.employeeID;
cout << setw(5) << "\n Please Enter Employees First Name: ";
cin >> info.firstName;
cout << setw(5) << "\n Please Enter Employees Last Name: ";
cin >> info.lastName;
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info.payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked:
";
cin >> info.hours;
}
cout << "\n\n \n";
cout << "ID" << setw(15) << "First Name" << setw(10) << "Last Name" <<
setw(10) << "Pay Rate" << setw(10) << "Hours";
cout << endl;
for (i = 0; i < j; i++)
{
cout << "\n" << info.employeeID << setw(15) << info.firstName << setw(10) << info.lastName << setw(10) << info.payRate << setw(10) << info.hours;
}
cout << "\n\n \n";
system("pause");
return 0;
};
#include <iostream>
#include <iomanip>
#include <string> //Allows you to use strings, which are way more handy for text manipulation
#include <vector> //Allows you to use vector which are meant to be rezied dynamicaly, which is your case
using namespace std;
struct Employee
{
int employeeID;
string firstName; //HERE : use string instead of char (string are array of char)
string lastName; //HERE : use string instead of char
float payRate;
int hours;
};
int main()
{
int j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
vector<struct Employee> info; //creation of the vector (dynamic array) to store the employee info the user is going to give you
for (int i = 0; i < j; i++) //declare your looping iterator "i" here, you will avoid many error
{
struct Employee employee_i; // create an employee at each iteration to associate the current info
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << "\n Please Enter The Employee ID Number: ";
cin >> employee_i.employeeID;
cout << "\n Please Enter Employees First Name: ";
cin >> employee_i.firstName;
cout << "\n Please Enter Employees Last Name: ";
cin >> employee_i.lastName;
cout << "\n Please Enter Employees Pay Rate: ";
cin >> employee_i.payRate;
cout << "\n Please Enter The Hours The Employee Worked: ";
cin >> employee_i.hours;
info.push_back(employee_i); //store that employee info into your vector. Push_back() methods expands the vector size by 1 each time, to be able to put your item in it
} // because you employee variable was create IN the loop, he will be destruct here, but not the vector which was created outside
cout << "\n\n \n";
for (int i = 0; i < j; i++) //the loop to get back all the info from the vector
{
cout << "ID :" << info[i].employeeID << " First Name :" << info[i].firstName << " Last Name :" <<
info[i].lastName << " Pay Rate :" << info[i].payRate << " Hours :"<< info[i].hours;
cout << endl;
//notice the info[i], which leads you to the employee you need and the ".hours" which leads to the hours info of that specific employee
}
system("pause");
return 0;
}
First, please read Tips and tricks for using C++ I/O (input/output). It might be helpful to understand C++ I/O.
Here are some comments on your code:
First
Use string instead of char.
struct Employee
{
int employeeID;
string firstName;
string lastName;
float payRate;
int hours;
};
Second
Use array of Employee object to store multiple employees.
Employee info[100];
Third
Use cin carefully depending data types. In your case, it would be something like this:
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info[i].employeeID;
cin.ignore(); //It is placed to ignore new line character.
cout << setw(5) << "\n Please Enter Employees First Name: ";
getline (cin, info[i].firstName);
cout << setw(5) << "\n Please Enter Employees Last Name: ";
getline (cin, info[i].lastName);
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info[i].payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked: ";
cin >> info[i].hours;
Fourth
std::getline() can run into problems when used before std::cin >> var. So, std::cin.ignore() can be used in this case to solve the problem.
I hope it helps.
I'm trying to read characters from std::cin using a char[] array.
Here is the simple program:
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main() {
int age, years;
char name[20];
cout << "Enter your age in years: " << endl;
cin >> years;
cout << "Enter your name in years: " << name[15] << endl;
age = years * 12;
cout << " Your age in months is: " << age << endl;
cout << "Your name is: " << name[15] << endl;
return 0;
}
And here what i get as an output
Enter your age in years:
19
Enter your name in years:
Your age in months is: 228
Your name is:
It doesn't recognizing the array from std::cin.
Anyone can help?
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main(){
int age , years ;
char name[20];
cout <<"Enter your age in years: "<< endl;
cin >> years;
cout <<"Enter your name in years: " <<endl;
cin >> name;
age = years*12;
cout << " Your age in months is: " << age <<endl;
cout << "Your name is: "<< name <<endl;
return 0;
}
There are two differences with your code:
cin << name;
(...)
cout << name << endl;
I'm assuming you thought
cout << "Enter your name" << name[15] << endl;
would make it ask for input. This is not what cout does. Cout prints out stuff on the console, it doesn't ask for input. That's cin's task.
Also you don't put [15] after the array name, this would just print out the 15th character in your array, which would be a garbage character as long as the name entered does not reach a length of 15.
int age, years;
char name[20];
cout << "Enter your age in years: " << endl;
cin >> years;
cout << "Enter your name in years: " << endl;
age = years * 12;
cin >> name;
cout << " Your age in months is: " << age << endl;
cout << "Your name is: " << name << endl;
cin.get();
I need help understanding the [Error] id return 1 exit status due to 2 undefined references: getGrades() and getAverage(). I was issued DEV C++ and knocked out the syntax errors with mild frustration but these "linking" errors are still giving me a hard time. This is the most recent update of the code, if anyone could help me understand these linking errors that would be great.
Compiler - Dev C++
Windows 7
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
// Function declarations
string getStudentName();
string getWork();
int getGrades();
double getAverage();
int main()
{
string studentName, work[3];
int grades[3];
double average;
// Get the name of the student
studentName = getStudentName();
// Get the work
work[3] = getWork();
// Get the grades
grades[3] = getGrades();
// Get the average
average = getAverage();
// Dynamic spacing for grades
ostringstream ss;
int gradesLength = ss.str().length();
ss <<setprecision(0) << fixed << showpoint;
ss << grades;
cout << "\n the average for " << studentName << " is: " << average << endl;
cout << "The grades for " << studentName << " are: " << endl;
cout << setw(30) << work[0] << ": " << setw(gradesLength) << grades[0] << endl;
cout << setw(30) << work[1] << ": " << setw(gradesLength) << grades[1] << endl;
cout << setw(30) << work[2] << ": " << setw(gradesLength) << grades[2] << "\n\n\n";
cout << "You have completed the program: \n";
return 0;
}
// Student Name
string getStudentName()
{
string name;
cout << "Enter students full name: ";
getline(cin, name);
return name;
}
// Assignments
string getWork()
{
string work[3];
cout << "\nEnter the name of each assignment \n";
cout << "First assignment: ";
getline (cin, work[0]);
cout << "Second assignment: ";
getline (cin, work[1]);
cout << "Third assignment: ";
getline (cin, work[2]);
return work[3];
}
// Grades
int getGrades(string work[3])
{
int grades[3];
cout << "\nEnter the grade for " << work[0] << ": ";
cin >> grades[0];
cout << "Enter the grade for " << work[1] << ": ";
cin >> grades[1];
cout << "Enter the grade for " << work[2] << ": ";
cin >> grades[2];
return grades[3];
}
// Math
double getAverage(int grades[3])
{
double average;
average = (grades[0] + grades[1] + grades[2]) / 3.0f;
return average;
}
I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)