Hello This may be a simple question and I am sorry for consuming your time for such a simple question but I am trying to learn c++. The following is a small program I am just practicing on as I learn. I have hit a snag in the code as when I execute it I get the following error: " In function 'int main()':
20:19: error: no match for 'operator!' (operand type is 'const string {aka const std::basic_string}')
20:19: note: candidate is:
20:19: note: operator!(bool)
20:19: note: no known conversion for argument 1 from 'const string {aka const std::basic_string}' to 'bool'
Further below you will find all of my code Thank you for the help!
#include
#include
using namespace std;
int main()
{
const string go = "tomato";
string Answer;
cout << "What is your friends favorite food?" << endl;
cout << "ENTER HERE:" << " " << flush;
cin >> Answer;
if(Answer == go)
{
cout << "Congratulations you know your friend!!!" << endl;
}
while(Answer =! go)
{
cout << "What is your friends favorite food?" << endl;
cout << "ENTER HERE:" << " " << flush;
cin >> Answer;
cout << "You do not know your friend please try again!!!" << endl;
}
return 0;
}
Answer =! go means Answer = (!go). The negation of go is undefined, as go is not bool.
What you probably want is a comparison for 'not equal', which is !=. The sequence of the two characters is significant.
The inequality comparison operator is !=, and not =!.
Change your code to this (in particular change the =! to !=
using namespace std;
int main()
{
const string go = "tomato";
string Answer;
cout << "What is your friends favorite food?" << endl;
cout << "ENTER HERE:" << " " << flush;
cin >> Answer;
if(Answer == go)
{
cout << "Congratulations you know your friend!!!" << endl;
}
while(Answer != go)
{
cout << "What is your friends favorite food?" << endl;
cout << "ENTER HERE:" << " " << flush;
cin >> Answer;
cout << "You do not know your friend please try again!!!" << endl;
}
return 0;
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
cin and getline skipping input [duplicate]
(4 answers)
Closed last year.
I was trying to make a program where the user is asked to give an input and it gives output with answered questions. Everything looks alright except that cin skipped my last question about school.
This is the original code:
//this program fills my data in profile
#include <iostream>
#include <string>
using namespace std;
int main () {
int age, exp_years;
char desired_grade;
string school_name, name;
const int year_grad = 4;
bool is_student;
cout << "You will need to enter your data for portfolio card" << endl;
cout << "Enter your last name" << endl;
cin >> name;
cout << "Enter your age" << endl;
cin >> age;
cout << "Enter your years of work experience" << "\n";
cin >> exp_years;
cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl;
cin >> is_student;
cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl;
cin >> school_name;
/* trying to make a function below */
cout << "Awesome, here is your info" << endl << "Your last name is "<< name << endl <<"You are "<<age << " years old." << endl << exp_years << " years of work experience" << endl;
if ( is_student == 1)
{
cout << school_name << " is lucky to have you!\n";
return 0;
} else {
cout << "Btw I am sure that " << school_name << " would be happy to have you as their student anytime\n";
return 0;
}
return 0;
}
I read some article and they said that getline() can help, so I tried to substitute with:
cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl;
getline(cin, is_student);
cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl;
getline(cin, school_name);
Hovewer, it gives me an error:
error: no matching function for call to 'getline'
What am I missing?
It seems the problem is related to entering a boolean value.
Here is shown how to enter boolean values
#include <iostream>
#include <iomanip>
int main()
{
bool is_student;
std::cin >> is_student; // accepts 1 as true or 0 as false
std::cout << is_student << '\n';
std::cin >> std::boolalpha >> is_student; // accepts strings false or true
std::cout << is_student << '\n';
}
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
This is the code :
#include <iostream>
using namespace std;
int main()
{
cout << " SSSSSSSSSSSSSSS" >> endl;
cout << " SS:::::::::::::::S" >> endl;
cout << "S:::::SSSSSS::::::S" >> endl;
cout << "S:::::S SSSSSSS" >> endl;
cout << "S:::::S" >> endl;
cout << "S:::::S" >> endl;
cout << "S::::SSSS" >> endl;
cout << " SS::::::SSSSS" >> endl;
cout << " SSS::::::::SS" >> endl;
cout << " SSSSSS::::S" >> endl;
cout << " S:::::S" >> endl;
cout << " S:::::S" >> endl;
cout << "SSSSSSS S:::::S" >> endl;
cout << "S::::::SSSSSS:::::S" >> endl;
cout << "S:::::::::::::::SS" >> endl;
cout << " SSSSSSSSSSSSSSS" >> endl;
cout << "IIIIIIIIII" >> endl;
cout << "I::::::::I" >> endl;
cout << "I::::::::I" >> endl;
cout << "II::::::II" >> endl;
cout << " I::::I" >> endl;
cout << " I::::I" >> endl;
cout << " I::::I" >> endl;
cout << " I::::I" >> endl;
cout << " I::::I" >> endl;
cout << " I::::I" >> endl;
cout << " I::::I" >> endl;
cout << " I::::I" >> endl;
cout << "II::::::II" >> endl;
cout << "I::::::::I" >> endl;
cout << "I::::::::I" >> endl;
cout << "IIIIIIIIII" >>
}
This is for school so don't ask why I am writing this code. But i get a lot of errors like the one in the title and I can't seem to find the problem so if anyone can help me, it'll be great!
When writing using the extraction or insertion operator (e.g >> or << respectively) you need to basically point it where you want the flow to go, and not change the flow for that whole statement, to put it in simple terms, in your case you want both insertion/extraction operators that you use to be facing like so << and that one is called an insertion operator.
This is the code you want:
#include <iostream>
using namespace std;
int main()
{
cout << " SSSSSSSSSSSSSSS" << endl;
}
and replicate that for as many times as you want there to be output statements.
Keep the flow going one direction and one direction only:
std::cout << "..." << std::endl;
You've got this going in and out at the same time.
You can't read from std::cout, it's for output only. It's an ostream which means it has no idea what >> even is. That operator isn't defined which is why you get that error.
I'm having some minor trouble with this basic C++ quiz program. In the main function, I have the user enter his/her name and I pass this string to the next function, take_quiz. However, I've noticed that if I include a name with a space in it (like a first and last name), an error occurs. For some reason, the amount of letters in the second word produces the same amount of displays of, "Please enter a valid answer (a, b, c, d)." I thought this was strange because that prompt can only occur when the inline function valCheck is used which is after the first cin of a variable in take_quiz. I need some help identifying the issue and correcting it. Thanks!
inline char valCheck(char& input)
{
tolower(input);
while(input < 97 || input > 100)
{
cout << "Please enter a valid answer (a, b, c, d):" << endl;
cin >> input;
}
}
int main(int argc, char *argv[])
{
string name;
cout << "This program will quiz your knowledge of C++. Please enter your name:" << endl;
cin >> name;
cout << "Hello " << name << "! IT'S QUIZ TIME!!!" << endl;
take_quiz(name);
system("PAUSE");
return EXIT_SUCCESS;
}
void take_quiz(string name2)
{
char quiz_results[10];
system("PAUSE");
cout << "\nThe quiz will now begin.\nThis quiz covers topics such as data types, arrays, pointers, etc." << endl
<< "To answer the multiple choice questions,\nsimply input a, b, c, or d according to the given options." << endl
<< "The test will continue regardless if you enter a question wrong or right." << endl
<< "Good luck " << name2 << "!" << endl;
system("PAUSE");
cout << "\n1. What preprocessor command must one include to use the cout and cin function?" << endl
<< "\na. #include <iomanip>" << endl
<< "b. #include <iostream>" << endl
<< "c. #include <cmath>" << endl
<< "d. using namespace std;" << endl;
cin >> quiz_results[0];
valCheck(quiz_results[0]);
Your valCheck() doesn't return anything - according to signature it needs to return a char value. You want to use std::getline(std::cin, str); instead of std::cin if your string contains newlines. std::cin will by default skip whitespaces. Also you're invoking take_quiz() without a prototype function before, so you need to move it above main() or specify the function signature at least above.
The complete program should look like this (you just need to add a check if quiz_results[0] is equal to 'b').
#include <iostream>
#include <string>
using namespace std;
inline char valCheck(char& input){
tolower(input);
while (input < 97 || input > 100){
cout << "Please enter a valid answer (a, b, c, d):" << endl;
cin >> input;
}
return input;
}
void take_quiz(string name2)
{
char quiz_results[10];
system("PAUSE");
cout << "\nThe quiz will now begin.\nThis quiz covers topics such as data types, arrays, pointers, etc." << endl
<< "To answer the multiple choice questions,\nsimply input a, b, c, or d according to the given options." << endl
<< "The test will continue regardless if you enter a question wrong or right." << endl
<< "Good luck " << name2 << "!" << endl;
system("PAUSE");
cout << "\n1. What preprocessor command must one include to use the cout and cin function?" << endl
<< "\na. #include <iomanip>" << endl
<< "b. #include <iostream>" << endl
<< "c. #include <cmath>" << endl
<< "d. using namespace std;" << endl;
cin >> quiz_results[0];
valCheck(quiz_results[0]);
}
int main(int argc, char *argv[]){
string name;
cout << "This program will quiz your knowledge of C++. Please enter your name:" << endl;
std::getline(std::cin, name);
cout << "Hello " << name << "! IT'S QUIZ TIME!!!" << endl;
take_quiz(name);
system("PAUSE");
return EXIT_SUCCESS;
}
I changed how to get string input from User
int main(int argc, char *argv[])
{
char name[100];
cout << "This program will quiz your knowledge of C++. Please enter your name:" << endl;
cin.getline(name,sizeof(name));
//cin >> name;
cout << "Hello " << name << "! IT'S QUIZ TIME!!!" << endl;
take_quiz(name);
system("PAUSE");
return EXIT_SUCCESS;
}
I am currently taking a C++ programming class and am working on a project in which I have to create a fairly simple movie database. My code essentially works as intended yet in certain cases it causes the main menu to loop infinitely and I cannot figure out why. I brought this to my teacher and he cannot explain it either. He gave me a workaround but I would like to know if anyone can see the cause of the problem. Full code is as follows:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct MovieType
{
string title;
string director;
int year;
int length;
string rating;
};
MovieType addMovie() {
MovieType newMovie;
cout << "Movie title :";
getline(cin, newMovie.title);
cout << "Director :";
getline(cin, newMovie.director);
cout << "Year :";
cin >> newMovie.year;
cout << "Length(in minutes) :";
cin >> newMovie.length;
cout << "Rating :";
cin >> newMovie.rating;
cout << endl;
return newMovie;
}
void listMovie(MovieType movie) {
cout << "______________________________________" << endl;
cout << "Title : " << movie.title << endl;
cout << "Director : " << movie.director << endl;
cout << "Released : " << movie.year << endl;
cout << "MPAA Rating : " << movie.rating << endl;
cout << "Running time : " << movie.length << " minutes" << endl;
cout << "______________________________________" << endl;
}
void search(vector<MovieType> movieVector) {
string strSearch;
cout << endl << "Search title: ";
getline(cin, strSearch);
for (int c = 0; c < movieVector.size(); c++) {
if (movieVector.at(c).title == strSearch)
listMovie(movieVector.at(c));
}
}
int main() {
bool quit = 0;
vector<MovieType> movieVector;
while (quit == 0) {
char selection = 'f';
cout << "Main Menu:" << endl;
cout << "'a' - Add movie" << endl;
cout << "'l' - List movies" << endl;
cout << "'s' - Search by movie title" << endl;
cout << "'q' - Quit" << endl;
cout << "Please enter one of the listed commands:";
cin >> selection;
cin.ignore();
cout << endl;
if (selection == 'a')
movieVector.push_back(addMovie());
else if (selection == 'l') {
for (int c = 0; c < movieVector.size(); c++) {
listMovie(movieVector.at(c));
}
}
else if (selection == 's') {
search(movieVector);
}
else if (selection == 'q')
quit = 1;
}
return 0;
}
When an unexpected input type is entered during the addMovie function(like entering text for the int type year), it just runs through the function then loops through the menu infinitely. It appears to me that the code just stops even looking at the input stream. I have tried using cin.ignore() in many different places but it doesn't matter if there is nothing left in the stream it just keeps going.
I am using NetBeans to compile my code.
I really have no idea why it behaves like this otherwise I would offer more information but I am just curious as to why this happens, because as I said before, my professor doesn't even know why this is happening.
Any help or insight is greatly appreciated.
cin enters an error state where cin.fail() is true. In this state it just ignores all input operations. One fix is to clear the error state, but better, only use getline operations on cin, not formatted input.
E.g., instead of
cin >> newMovie.year;
… do
newMovie.year = stoi( line_from( cin ) );
… where line_from can be defined as
auto line_from( std::istream& stream )
-> std::string
{
std::string result;
if( not getline( stream, result ) )
{
// Throw an exception or call exit(EXIT_FAILURE).0
}
return result;
}
Disclaimer: code untouched by compiler.
I am a very newbie programmer, so I don't really know much about writing code to protect the application.. Basically, I created a basicMath.h file and created a do while loop to make a very basic console calculator (only two floats are passed through the functions). I use a series of if and else if statements to determine what the users wants to do. (1.add, 2.subtract, 3.multiply, 4.divide) I used a else { cout << "invalid input" << endl;} to protect against any other values, but then I tried to actually write a letter, and the program entered a infinite loop. Is there anyway to protect against users who accidentally hit a character instead of a number?
`#include <iostream>
#include "basicMath.h"
using namespace std;
char tryAgain = 'y';
float numOne = 0, numTwo = 0;
int options = 0;
int main()
{
cout << "welcome to my calculator program." << endl;
cout << "This will be a basic calculator." << endl;
do{
cout << "What would you like to do?" << endl;
cout << "1. Addition." << endl;
cout << "2. Subtraction." << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division." << endl;
cin >> options;
if (options == 1){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
}
else if (options == 2){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
}
else if (options == 3){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
}
else if (options == 4){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
}
else {
cout << "Error, invalid option input." << endl;
}
cout << "Would you like to use this calculator again? (y/n)" << endl;
cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
`
One way would be to use exception handling, but as a newbie you're probably far from learning that.
Instead use the cin.fail() which returns 1 after a bad or unexpected input. Note that you need to clear the "bad" status using cin.clear().
A simple way would be to implement a function:
int GetNumber ()
{
int n;
cin >> n;
while (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Not a valid number. Please reenter: ";
cin >> n;
}
return n;
}
Now in your main function wherever you are taking input, just call GetNumber and store the returned value in your variable. For example, instead of cin >> numOne;, do numOne = GetNumber();
When you input to cin, it is expecting a specific type, such as an integer. If it receives something that it does not expect, such as a letter, it sets a bad flag.
You can usually catch that by looking for fail, and if you find it, flush your input as well as the bad bit (using clear), and try again.
Read a whole line of text first, then convert the line of text to a number and handle any errors in the string-to-number conversion.
Reading a whole line of text from std::cin is done with the std::getline function (not to be confused with the stream's member function):
std::string line;
std::getline(std::cin, line);
if (!std::cin) {
// some catastrophic failure
}
String-to-number conversion is done with std::istringstream (pre-C++11) or with std::stoi (C++11). Here is the pre-C++11 version:
std::istringstream is(line);
int number = 0;
is >> number;
if (!is) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
} else if (!is.eof()) {
// line is a number, but ends with a non-number, e.g. "123abc",
// whether that's an error depends on your requirements
} else {
// number is OK
}
And here the C++11 version:
try {
std::cout << std::stoi(line) << "\n";
} catch (std::exception const &exc) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
std::cout << exc.what() << "\n";
}