I just started teaching myself C++ on the Mac, and I have run into some issues.
I have written some code that allows the user to enter a number and when they hit enter, the number will be returned to the user.
Xcode will absolutely not have it though. Every time I try to run my code, it says that there is an issue with the cin>> thisisanumber; code.
The error comes up and says
Invalid operands to binary expression. Error is on line 10.
What am I doing wrong?
#include <iostream>
using namespace std;
int main()
{
int thisisanumber();
cout << "Please enter a number: ";
cin >> thisisanumber;
cin.ignore();
cout << "You entered"<< thisisanumber <<"\n";
cin.get();
}
You've fallen victim to the most vexing parse, which means thisisanumber is being treated as a function. Take out the parentheses and you should be fine:
int thisisanumber;
Also consider making it a bit more readable, such as thisIsANumber. If you ever need to know it, thisIsANumber uses the camel-case naming convention.
Declare your variable without brackets, like
int thisisanumber;
With brackets, it is interpreted as a function, and a function can't be passed as a parameter to the >> operator.
Your problem is the so called most vexing parse. Basically everything, which could be parsed as a function declaration will be parsed as such. Therefore the compiler will interpret int thisisanumber(); as a declaration of a function thisisanumber taking zero arguments and returning an int. If you consider this behaviour the problems with cin>>thisisanumber; should be somewhat selfevident.
If you remove the parantheses, changing the variable declaration to int thisisanumber;, your program should behave like you'd expect it to with thisisanumber being a variable of type int.
You might however reconsider your naming conventions, thisisanumber isn't exactly readable. I would suggest going with this_is_a_number, thisIsANumber or ThisIsANumber.
int thisIsANumber;
try making it variable declaration because what you wrote has been interpreted as function.
delete () after thisisanumber, because () after thisisanumber means that it's a function, when it's not.
Related
So, my programming instructor asked me to try putting a cout-statement as the condition for an if-statement and see what happens. I tried it (just made a random code) and didn't notice anythimg special. Here's the code.
#include<iostream>
using namespace std;
int main()
{
int x=1;
int y=2022;
if(cout<<"Covid")
{
cout << "\n Us \n";
x=y;
cout << x;
}
}
The output is simply
Covid
Us
2022
What I don't understand is why this would be used. From my amateur understanding, even if I used an else-statement or any amount of else-if statements, they wouldn't run, since the condition for the if-statement is self-fulfilling. I could the simply write the whole code directly without using an if-statement. What then, could be the purpose of using an if-statement? Any general use?
Prior to C++11, when you write if(cout << "Covid"), there is an implicit conversion to void*. This value is unspecified by the C++ standard, other than if the stream is in an error state, then nullptr is returned.
From C++11, the implicit conversion is to bool. false denotes the stream is in an error state, true otherwise.
Note that you must have imbued a very funky iostream-derived object indeed for the output to be "Pakistan" given your input!
This question already has answers here:
c++ change function's variable argument
(2 answers)
Closed 2 years ago.
I created a function which takes a string for a message and an input value (primarily an integer, at least in this case) so I can print a message and take an input in a single function instead of two lines of code. Here is the snippet:
main.h
void input(std::string msg, int choice) {
std::cout << msg;
std::cin >> choice;
}
However, when passing the function in my main function, it doesn't perform the same way this would:
main.cpp (working code with expected result)
int initial_choice;
std::cout << "Invalid input provided. Please try again: ";
std::cin >> initial_choice;
main.cpp (working code with unexpected result)
int initial_choice;
input("Invalid input provided. Please try again: ", initial_choice);
When it comes to the snippet with the expected result, my switch case function properly detects the input (in this case it is initial_choice) as a valid integer. For example, entering 1, 2, or 3 will work with case 1:, case 2:, and case 3:. However, the snippet with the unexpected result doesn't detect any of the three valid numbers in my switch case function, instead they all run the code under the default case.
This has nothing to do with cin, cout, switch statements, etc.
As user202729 has pointed out, it is a simple matter of function parameter-passing.
C++ is not Fortran III; by default, parameters to functions are passed by value, not by reference. This means that if within a function you change the value of one of its parameters, this change will only be in effect within the function; the change will not be reflected to the caller.
So, your std::cin >> choice; statement works perfectly well, and it stores the value entered by the user in your choice variable. However, this value forever ceases to exist once the function ends, and it is never reflected back to the caller, which in this case is the initial_choice variable of your main() method.
To fix this, you have two options:
Pass the variable by reference, so that the function can modify it.
Do not pass the variable at all; instead, have the function return the value; that's generally what functions are for.
I'm trying to understand why does the following code compile?
#include<iostream>
using namespace std;
int main ()
{
int cin;
cin >> cin;
cout << "cin" << cin;
return 0;
}
How is the compiler able to distinguish in the statement: "cin >> cin"?
If you run the program, you'll notice that it never waits for input.
It doesn't distinguish anything – you're right-shifting the int by its own value.
(And that value is indeterminate, so the program is undefined.)
If you increase the warning level of your compiler, you should see "Warning: statement has no effect" or something to that effect.
To add on to molbdnilo's answer:
When you are using the statement using namespace std;, you are telling the compiler that for all variables in the current scope, loop up the identifier in current scope, if not, look up in the parent scope, until the look up reaches global scope and still unable to find the identifier, then it will try to find it in the namespace you are using.
After you declared int cin, everything that is called cin in the main function will be the local int cin not the std::cin, so all of your codes are just left shifting cin and shifting "cin" by cin amount of bits.
I'm trying to write a simple test program in VS 2013. It's telling me that scanf() is unsafe, and that I should use scanf_s() instead. Even worse, it's telling me that int x is uninitialized (and not just as a warning, as an error), even though it doesn't need to be initialized there. I'm wondering if it's possible to change settings so that VS2013 does not give me these error messages, or figure out what I am doing wrong.
#include <stdio.h>
int main(){
printf("How many pizzas did you make: ");
int x;
scanf("%d", x);
}
use cout instead of printf() and cin instead of scanf
example:
const int SIZE = 5;
char word[SIZE];
cout << "Enter a word: ";
cin >> setw(SIZE) >> word;
cout << "You entered " << word << endl;
don't forget to import the std library
using std;
you may be making mistake in the this line
scanf("%d", &x);
scanf is warned as unsafe because it may cause buffer overflow. And scanf needs address of x, so it should be &x.
There is one outright error and a probable bug in your example code:
scanf("%d", x);
The above needs a pointer, and you must always verify that all output parameters were matched.
To the second, Microsoft is behind the drive to force you to abandon the standard C library functions, going so far as to declaring their use an unsupportable risk, not that the safer functions in an optional part of the C standard cannot be used in an unsafe manner too.
Look in the compiler documentation, there is a flag to suppress this irritating behavior.
Anyway, you are writing in C++, so just about everyone here will say you should use iostreams and idiomatic C++, regardless of how you ask or why.
This code is C/C++ and runs without warnings or debug messages. I'm using Code::blocks with the GNU GCC compiler. This app worked perfectly once, then somewhere along the lines I messed up without noticing. Now every time it will allow a ip address input, but then freeze up and close. Why?
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int ip[3];
char * inputIP;
int x;
string classValue;
void subnetClass()
{
if (x==0) classValue="Error: first octet may not be zero.";
if (x>0 && x<=126) classValue="Class A";
if (x==127) classValue="Loopback Address";
if (x>=128 && x<=191) classValue="Class B";
if (x>=192 && x<=223) classValue="Class C";
if (x>=224 && x<=239) classValue="Class D";
if (x>=240 && x<=255) classValue="Class E";
if (x>255) classValue="Error: an octet may not be more than 255.";
cout << classValue << endl;
}
int main()
{
cout << "Enter IP address in dotted-decimal form." << endl;
cin >> inputIP;
scanf(inputIP, "%d.%d.%d.%d" , &ip[0],&ip[1],&ip[2],&ip[3]);
int x=ip[0];
subnetClass();
return 0;
}
Build Log:
Checking for existence: C:...\IP subnetting app\bin\Debug\IP subnetting app.exe
Executing: "C:...\CodeBlocks/cb_console_runner.exe" "C:...\IP subnetting app\bin\Debug\IP subnetting app.exe" (in C:...\IP subnetting app.)
Process terminated with status -1073741510 (0 minutes, 27 seconds)
You are declaring a variable 'x' that is hiding the global one.
int x=ip[0];
However, don't do it this way. Add an int parameter to subnetClass and pass in the value that way, and remove the global variable.
Really, removing all of your globals should be a goal and easy to accomplish. Several are only used in main().
It might have worked with a little help from sheer luck even if you messed things up later, I believe. More or less everything is wrong. First you read the line into the area pointed to by uninitialized pointer (or maybe you read the pointer value, I'm not even sure what >> (char*) is supposed to do). You better change the definition to
std::string inputIP;
then you try to parse it used scanf and pass this pointer as a format string. What you meant is using sscanf. Assuming you changed the inputIP type, you can use
sscanf(inputIP.c_str(),"%d....
Then you assign to local main variable x that shadows global, which remains uninitialized when you use it in the function. Just remove the int part in the assignment like this:
x=ip[0];
and make the ip array of four elements.
int ip[4];
Then it may work. Unless I missed something else.
And one more thing: if you use some source control (for instance using git you may start new project in no time) then you'd know what you've changed when you mess up, just commit early, commit often.
Use sscanf instead of scanf