I have a question regarding using getline with and If/ Else If statement.
Currently, my code looks like this:
int yourAge = 13;
cout << "What's your age dude? ";
if(yourAge < 21) {
cout << "What? " << yourAge << "? You're too young to drink!!! " << endl;
} else if(yourAge >= 21) {
cout << "Cool!" << yourAge << "? You are good to go. Don't drink and drive!" << endl;
}
return 0;
}
This works fine. yourAge is 13 and the result is that it says "You're too young to drink".
However, I want to introduce the getline function into the code, so that the result depends upon the user's input. I attempted to change code as below:
int yourAge;
cout << "What's your age dude? ";
getline(cin, yourAge);
if(yourAge < 21) {
cout << "What? " << yourAge << "? You're too young to drink!!! " << endl;
} else if(yourAge >= 21) {
cout << "Cool!" << yourAge << "? You are good to go. Don't drink and drive!" << endl;
}
return 0;
}
This, in turn, results in this error message whenever I try to compile:
"ctut.cpp: In function ‘int main()’:
ctut.cpp:25:25: error: no matching function for call to ‘getline(std::istream&, int&)’
getline(cin, yourAge);
^
ctut.cpp:25:25: note: candidates are:
In file included from /usr/include/wchar.h:90:0,
from /usr/local/include/c++/4.9.2/cwchar:44,
from /usr/local/include/c++/4.9.2/bits/postypes.h:40,
from /usr/local/include/c++/4.9.2/iosfwd:40,
from /usr/local/include/c++/4.9.2/ios:38,
from /usr/local/include/c++/4.9.2/ostream:38,
from /usr/local/include/c++/4.9.2/iostream:39,
from ctut.cpp:1:
/usr/include/stdio.h:442:9: note: ssize_t getline(char**, size_t*, FILE*)
ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);....."
That's just the beginning, it goes on for quite a while.
Any help would be appreciated on how to modify. I would like to get the user input on user age, and depending upon the input, to spit out the correct message on the screen.
Thank you!
Quoting cppreference.com,
getline reads characters from an input stream and places them into a string.
Hence getline() will work only if your variable yourAge is a std::string.
For reading int, std::cin is more than enough.
if you must use "getline()" for whatever reason, you have to convert the string to int:
int yourAge;
string age;
cout << "What's your age dude? ";
getline(cin, age);
yourAge = stoi(age);
if(yourAge < 21) {
cout << "What? " << yourAge << "? You're too young to drink!!! " << endl;
} else if(yourAge >= 21) {
cout << "Cool!" << yourAge << "? You are good to go. Don't drink and drive!" << endl;
}
return 0;
getline() is used to read strings not integers. You are better off using cin>>yourAge; for this program. Read these links to learn more about getline link1 link2
You can use getline() to read integers, but it is not advisable. It is better to read integers using cin.
If you want to read integers using getline(), don't forget to convert them into integers using stoi().
Related
How do I multiply a function to another function? and how do I properly use parameters?
I'm not exactly sure, I am really new to C++ with only about 14 weeks of class time.
Something I've tried would be creating a new function meant to multiply other functions and in the arguments I would put in the functions names.
For example:
float mealMath(numberOfAdults, mealChoosing){
//Rest of function
}
but I always get an error.Please explain how to fix this, this is a big obstacle in programming for me and I can't seem to grasp how to fix this or go about doing these things. Don't be to harsh on me for this.Thanks!
int numberOfAdults(){
int totalAdults;
cout << "Now how many adults will there be?: ";
cin >> totalAdults;
cout << "It seems there will be: " << totalAdults << " Adults." << endl;
while(totalAdults < 1){
cout << "Sorry there has to be a minimum of 1 adult!" << endl;
cout << "How many adults: ";
cin >> totalAdults;
}
return 0;
}
int numberOfKids(){
int totalKids;
cout << "Now how many Kids will there be?: ";
cin >> totalKids;
cout << "It seems there will be: " << totalKids << " kids." << endl;
while(totalKids < 0){
cout << "Sorry there has to be a minimum of 1 Kid!" << endl;
cout << "How many Kids: ";
cin >> totalKids;
}
return 0;
}
float mealChoosing(){
float cost;
string mealChoise;
cout << " " << endl;
cout << "Now, What meal will you be getting(D/S): ";
cin >> mealChoise;
if(mealChoise == "D"){
cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
cost = 25.95;
}
if(mealChoise == "S"){
cout << "It seems you have selected the Standard Meal plan for everyone!" << endl;
cost = 21.75;
}
cout << " " << endl;
return cost;
}
One expected result is I want to multiply the input that the user gives in function "numberOfAdults" to the input a user gives for "mealChoosing"
So I want numberOfAdults * mealChoosing but I want that done in a different function so
"float total(){
float totalBill;
totalBill = numberOfAdults * mealChoosing;
cout << totalBill;"
or something along those lines. I can't complete this project because I can't for some reason properly give the functions the proper information needed in parameters.
In this case(and most) you should not declare a function whose parameters are functions. Instead declare mealMath with an integer and a float input:
float mealMath(int a, float b){/*Your code here*/}
And then later call mealMath with the other two functions passed as arguments.
float x = mealMath(numberOfAdults(), mealChoosing());
Alternatively you can have no function parameters for mealMath() and instead call numberOfAdults() and mealChoosing() from inside of the function.
It's important to note that most of the time you'll be calling a function and using its output as an argument, and therefore you'll need to put the () after the function's identifier, instead of just typing the identifier alone.
Like mealChoosing() return totalAdults and totalKids (although its not needed here) from numberOfAdults(), numberOfKids() respectively.
int numberOfAdults() {
//...
return totalAdults;
}
int numberOfKids() {
//..
return totalKids;
}
float mealChoosing() {
//..
return cost;
}
Now on mealMath(numberOfAdults, mealChoosing)
float mealMathOutput = mealMath(numberOfAdults(), mealChoosing());
I'm trying to create a command menu where the user will be able to perform as many commands as he/she wants until pressing "q" which will end the loop. I think I have everything I need to do this except I realized mid-way that my professor asked to use string. When I included string into the program, I began to get error messages saying "could not convert string to bool" wherever there was a while or if statement. What can I do to fix this problem and get my program working. Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char option;
char number=0;
string s;
string n;
string p;
string q;
char number2;
cout << " Please enter a number: "<< endl;
cin >> number;
do {
cout << " Please enter a command: " << endl;
cout << " s- square the number " << endl;
cout << " n- add the number and (number +1) " << endl;
cout << " p- add the number and (number -1) " << endl;
cout << " q- quit" << endl;
cin >> option;
if (option=s) {
s= number*number;
cout << "Square of this number is : " << s;
}
else if ( option=n){
number2= number+1;
n= number+number2;
cout << "Sum of" << number << "+" << number2 << "is: " << n;
}
else if (option=p) {
number2= number-1;
p= number+number2;
cout << "Sum of" << number << "+" << number2 << "is" << p;
}
else if (option=q)
cout << "Terminating Program";
} while(option);
return 0;
}
you're assigning in the if and else if rather than comparing.
if (option=s) {
should be
if (option=='s') {
note the double =
Also, you need to put single quotes (') around the character choice.
It's a common mistake that even experienced developers make.
These declarations
char number=0;
string s;
string n;
string p;
string q;
char number2;
should all be int
int number=0;
int s;
int n;
int p;
int q;
int number2;
Let me answer as if I were who will evaluate your homework. You have several issues here:
You are asked to use string. Avoid the use of char and string together.
char option; // professor asked to use string: (-1) point
string option; // ok
When you use a single =, like in option="a", you are assigning the value "a" to the variable option. But in the if-else statements you want to compare, so you should use the == comparison operator. Also, you can't compare a char with a string.
if(option = "a") // error: expression must have bool type: (-2) points
if(option == 'a') // error: no operator "==" matches std::string == char; (-2) points
if(option == "a") // ok
You use while(option), but option is declared as a char, not as a bool. Replace this line to while(option!="q") to finish when you enter q.
while(option); // error: expression must have bool type; (-2) points
while(option != "q"); // GOOD!
Also, your program will finish when you scape from the while-statement; so, try to put the "Terminating Program" message after this.
You do not need to declare such many variables (s, n, p, q, number2). Try to use temporary variables inside each scope, for example:
if (option=="s")
{
cout << "Square of this number is : " << number*number << endl;
}
else if ( option=="n")
{
int number2= number+1;
cout << "Sum of " << number << "+" << number2 << " is : " << number+number2 << endl;
}
In the form you write this code, every time you type a new option you will obtain an output like:
Sum of 10+11 is : 21 Please enter a command:
This is ugly to me (-1 point). Try to put a newline (<< endl;) after every cout lines.
Finally, what if I type any other letter not listed in the menu? I would expect a message like Enter a valid option (-1 point).
simple program tells u how much milk costs whatever i dont get why i get this error "no match for 'operator>>' in 'std::cin??" im a beginner at c++ but still what the hell.
also this error: "In function 'int main()':"
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
const double CARTONLOAD = 3.78;
const double CARTONCOST = 3.78 * .38;
const double CARTONPROFIT = 0.27;
int main()
{
double totalmilk = 0;
double milkcartonsneeded = 0;
double milkcost = 0;
cout << "Enter total amount of milk produced in the morning in Liters" << endl;
cin >> totalmilk >> endl;
milkcartonsneeded = totalmilk/CARTONLOAD;
cout << " Number of milk cartons needed to hold milk: " << milkcartonsneeded << endl;
milkcost = milkcartonsneeded * CARTONCOST;
cout << " The cost of producing milk is: " << milkcost << endl;
cout << " The profit for producing milk is: " << milkcartonsneeded * CARTONPROFIT - milkcost << endl;
return 0;
}
endl is an output stream manipulator. cin is an input stream. I'm not sure what you expect endl to do here:
cin >> totalmilk >> endl;
But it's wrong.
This is the problem
cin >> totalmilk >> endl;
It is giving error because of endl. Remove it.
operator<< has an overload that takes a function pointer to a function that receives an std::basic_ostream. This allows you to use "stream manipulators", i.e. std::endl, in a operator<< chain. This allows you to do the following for example:
std::cout << "hey.";
std::endl(std::cout);
std::cout << "hello.";
Because std::endl is just a function that takes a std::basic_ostream. However, it also returns one by reference (similar to operator<<), meaning it can appear in a chain, i.e. std::cout << std::endl.
Since std::cin is a std::basic_istream, you have incompatible arguments.
I am trying to write a console utility for maintaining a court date list in .txt format so I can keep better and easier track of them. To that effect I started with a piece of code I liked, as a template, and worked my way upwards.
The problem I am encountering is with implementing a search function that goes through the whole file and lists all found occurrences of a string (namely a calendar type date stored in the format DDMMYY).
Sorry if my coding is far from being acceptable, but keep in mind that I'm just a computer passionate lawyer! :)
Without further jib-jabbing here is the code in question:
#include "stdafx.h"
using namespace std;
void name();
void ID();
int main()
{
system("cls");
system("color 0F");
int ch1;
cout << "1 pentru a introduce un termen nou" << endl;
cout << "2 pentru a cauta o data" << endl;
cin >> ch1;
if (ch1 == 1)
{
name();
}
else if (ch1 == 2)
{
ID();
}
}
void name()
{
system("cls");
string name, salary;
ofstream worker("termene.txt", ios::app);
int ID;
cout << "Termen la instanta : ";
cin >> name;
cout << "Data termenului format ZZLLAA : ";
cin >> ID;
cout << "Client : ";
cin >> salary;
worker << name << " " << ID << " " << salary << endl;
worker.close();
cin.get();
main();
}
void ID()
{
ifstream worker("termene.txt");
string name, salary, ID;
unsigned int curLine = 0;
string search;
cout << "Introdu data format ZZLLAA : ";
cin >> search;
string line, line2, line3;
if (worker.is_open())
{
while ((getline(worker, line)))
{
if (line.find(search, 0) != string::npos)
{
cout << "Termen: " << endl;
cout << line << endl;
if (line.find(search, 1) != string::npos)
{
getline(worker, line2);
cout << "Termen: " << endl;
cout << line2 << endl;
if (line.find(search, 2) != string::npos)
{
getline(worker, line3);
cout << "Termen :" << endl;
cout << line3 << endl;
}
}
else
{
system("cls");
cout << "Bad command or court date." << endl;
}
}
worker.close();
}
system("pause");
main();
}
}
Call main() does not look like a good idea. It can potentially create a endless loop which will consume the function call stack. Here the growing is limited by escaping standard input, but it still overloads and may overflow the call stack. Bad practice, avoid it. Create a while loop within main().
The following code will prevent call stack overflow:
int main() {
while(true) {
// Branch your code
}
return 0;
}
Then, each time a function is called within the while loop, the call stack is released when the function exits. Therefore the stack does not grow forever and you avoid the stack overflow. By the way it is better to provide an exit condition instead of creating an endless loop.
Why don't you use fgrep? of course this will only work on Unix.
fgrep COMMAND:
fgrep command is used to search one or more files for lines that match
the given string or word. fgrep is faster than grep search, but less
flexible: it can only find fixed text, not regular expressions.
I think you can use UnixUtils to get a few commands on Windows as well.
I posted an earlier question asking for help with using a validation script in my code. After a very helpful answer I was able to sort of figure out how I needed to proceed. Well, I've hit a big obstacle;
#include <iostream>
#include <sstream>
#include <string>
#include <ctype.h>
using namespace std;
int main()
{
unsigned __int64 input = 0;
int n, i;
char str[]="c3po...";
i=1;
n=0;
for (cout << "Input a number" << endl; cin >> input; cin.ignore(numeric_limits<int>::max(), '\n'))
{
cout << "We're parsing your input '" << input << "'\n";
if (input % 2 == 0)
{
cout << "Even!" << endl;
}
else if (input % 2 == 1)
{
cout << "Odd" << endl;
cout << "Lets make it even shall we? " << "Your new number is... " << input + 1 << endl;
}
else (isalnum(str[i]));i++;
{
cout << "We could not parse '" << input << "' as a number.\n";
}
}
system ("pause");
return 0;
}
As you can see from my code, the validation script is well, sort of working. I have some bugs I wish to iron out.
1- When I input a number, it runs though the code as it should but it also displays
Could not parse 'inputted number' as a number
obviously when a number is inputted you don't want this to happen!
2- For the error message, it is showing the inputted number as [0]. Is this to do with using an integer? How can this be fixed?
Thanks!
your problem is quite simple, you have small mistake on this line
else (isalnum(str[i]));
Your else statement ends at the semicolon and does actually nothing. Following statements will be executed every time.
i++;
{
cout << "We could not parse '" << input << "' as a number.\n";
}