How to read number from a console without any variables - c++

I know that for reading from console we can use
int number;
cin >> number;
//A line of code where we use int number
But is it possible to read a number from console without any variables. Are there any methods that return a number from console?

But is it possible to read a number from console without any variables.
Read a number without using any variable – sounds like a puzzle.
Here we go:
#include <iostream>
int main()
{
return !std::cin.operator>>(*new int());
}
This program returns
0 … on success (input was a number)
1 … on error (input was not a number).
Output:
Test 123:
Error: 0
Test abc:
Error: 1
Live Demo on coliru
Note:
I somehow had to provide a temporary LValue to the stream input operator.
I had no better idea than *new int() though I know this makes a memory leak.
In this simple program, this won't hurt as the OS will make the clean-up for me.
Are there any methods that return a number from console?
This part was really unclear to me.
If I had this problem on my own I would make a helper function
int readNum(std::istream &in)
{
int number; in >> number; return number;
}
which I could use then in the main() function without any variable
int main()
{
std::cout << "Number: " << readNum(std::cin) << '\n';
}
but readNum() had again to use a variable to store the result of formatted input.
It's hard to use formatted input stream operators without any variable if the result of input should be accessed again (at least, in C++ with std library only).

The getchar() function allows you to ignore one character instead of using a variable to save the value.

Related

Returning input in C++

I'm very new to C++ and was wondering if there was a way to return integer input from a function directly without storing it in a variable.
To be more clear:
#include <iostream>
int function()
{
std::cin >> (return function here???)
}
int main()
{
int number = function()
std::cout << number
return 0;
}
Thanks for any help.
if there was a way to return integer input from a function directly without storing it in a variable.
There is not. All standard input interfaces take an object argument which they modify rather than return the resulting value1.
A possible reason for this design is that it is very typical for input to be bad. Only way to avoid returning an int from a function declared to return int is to throw (or terminate the process, but that would be silly). And input error is perhaps considered so non-exceptional that using exceptions for control flow of input handling may be considered inappropriate. This is just my reasoning, not an authoritative explanation for the design choice.
If you fix your function to be correct, with the variable that is necessary and checking for errors, then you can use that function to do exactly that:
return function();
1 With the exception of std::istream::get() and the corresponding C style std::getc and std::fgetc which you can use to extract a single character that they return directly.

How to handle exceptions when a number might overflow the range of specific data type in C++?

I am making a program in C++ that is supposed to calculate the arithmetic results based on the user input. I want to handle it very closely if a user enter a huge value that an int double and float cannot handle then I throw an exception of overflow data. How can I handle these types of exceptions.
The second part is if a user gives me two number and after multiplication or addition, the resulting number might be much bigger than the range of specific data type that how we can handle this type of exception as well?
You can use numeric_limits to do some checks before doing the arithmetic operation.
For instance a function that adds two int. You could do something similar to this:
int AddInt(int a, int b)
{
if (a>0 && b>0)
{
// May overflow
if (a > std::numeric_limits<int>::max() - b)
{
// Will overflow
throw ....something....
}
}
else if (a<0 && b<0)
{
// May overflow
if (a < std::numeric_limits<int>::min() + b)
{
// Will overflow
throw ....something....
}
}
// We are good - no overflow
return a+b;
}
SafeInt library does something like that. It provides template classes that act like regular integers but have checks on all operations for overflow etc.
You can read an article on codeguru:
Improve Microsoft Visual C++ Application Security and Robustness with SafeInt. It's maintained by microsoft, but it's not windows-only and should most likely be portable.
With SafeInt basically you write regular code and replace int with safeint and all mathematical operations will be automatically checked for overflows. Not sure if there are specializations for doubles though. Perhaps you may take similar idea and write your own wrappers to suite your needs, or you may simply use safeint with 128-bit integers and allocate 64 bits for fractional part and 63 for integer part and have very precise calculations that are always checked.
Beside these answers, you may be interesting in validating the input itself.
In this case you can:
read the input as string
validate it
(make sure that only numerical characters included like '0'-'9' , '+' , '-',
and the decimal-point)
check it against the limits.
if all of the above succeed, convert the string into the numerical value.
These requires a lot of functions and logic to accomplish. I think it is not a trivial task.
Alternatively, you can use <sstream> header functions to do it for you.
Here is an example code:
#include <iostream>
#include <sstream>
using namespace std;
template <typename T>
bool is_valid_numerical_input(T& num)
{
string str_num;
cout << "\n Enter a number: ";
cin >> str_num;
stringstream sn(str_num);
if (!(sn >> num))
return false;
return true;
}
int main()
{
short number;
if (is_valid_numerical_input(number))
cout << "\n Your number is: " << number;
else
cout << "\n Invalid input";
cout << "\n\n\n";
}

Are the values of cin held somewhere?

Write the definition of a function named copy that reads all the
strings remaining to be read in standard input and displays them, one
on a line with no other spacing, onto standard output. Do not use loops of any kind (for, while, etc.).
I've tried something like:
void copy()
{
string x;
getline(cin, x);
cout << x << "\n";
if(cin){
copy();
}
else{
return;
}
}
But I may not be understanding entirely what "all the string remaining to be read in standard input" means. Can someone help me out?
Recursion is the right idea to satisfy teacher's strange limitations however look into std::getline and the operators and methods of std::cin for correct usage if you'd like to store the input in variables etc. Currently the value read is being stored in the temporary string named x for each scope of the function call on stack.
Edit: There is nothing particularly wrong with what you have although you technically don't need the else case as the stack will unwind after last call to copy(); and since it's a void function no return is necessary.
void copy()
{
{ // create a scope...
string x;
if (getline(cin, x))
cout << x << "\n"; // don't output 'x' when getline fails!
} // let x go out of scope - less baggage during recursion...
if(cin)
copy();
}
The question's a bit vague...
...reads all the strings remaining to be read in standard input and displays them, one on a line with no other spacing, onto standard output.
Is a "string" necessary the same as a line? One reason I suspect not is because if it is, the question's even less interesting (and you didn't think it possible!) - a reasonable answer:
std::cout << std::cin.rdbuf();
Another reason is "no spacing"... perhaps that's referring to leading and trailing space on each line, or maybe the intention was that each space separated value be considered a string, in which case you'd need:
void copy()
{
{
string x;
if (cin >> x);
cout << x << "\n";
}
if (cin)
copy();
}
Anybody's guess which is wanted....

Is it okay to return vector in main

I am wondering is it okay to return a vector in main()? For example,
aSpecialVectorType main()
{
aSpecialVectorType xxx(vector::zero);
// do something here;
return xxx;
}
Do I need to forward declare "class aSpecialVectorType;" before main()?
And btw, is it legal to use another name other than "main" in c++?
Thanks
Edit1:
If not, what is the best way that it can output a vector?
My friend ask me to give him a blackbox that can serve as "vector in and vector out", he will use his matlab code to call my code. That's why I am asking.
I know how to vector in, but not sure if there is an easy way to output a vector.
Thanks
Edit2:
I am surprised why C++ has such an standard, any explanation? :)
In C++, main needs to return an int:
C++ standard, 3.6.1.2:
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined.
.
If not, what is the best way that it can output a vector?
To output a vector, you need to copy it to a file or an output stream:
ostream_iterator<int> out_it(cout, ", ");
copy(myvector.begin(), myvector.end(), out_it);
The code fragment above writes the content of vector<int> to the standard output.
No. main must be declared in one of these two ways:
int main()
or
int main(int argc, char*[] argv)
Anything outside of this is not standard.
No.
According to the standard main() must return an int and only that.
No.
main must return int.
Other functions are free to have other names and return anything they want.
To expand on dashblinkenlight's answer, here is how two programs can communicate. Not by one capturing the return value of the other, but by a process called "piping", directing the standard output of one program to the standard input of another. Here, I'll print out a list of strings in one program, then the other program will expect a list of strings on its standard input, then I'll show you how to use the two together:
// Output program
#include <vector>
#include <string>
#include <iostream>
int main()
{
using namespace std;
vector<string> v;
v.push_back("one");
v.push_back("two");
v.push_back("three");
for (int i=0; i<v.size(); ++i)
cout << v[i] << '\n';
}
// input program
#include <iostream>
#include <vector>
#include <string>
int main()
{
using namespace std;
vector<string> v;
for (string tmp; cin >> tmp; )
v.push_back(tmp);
// print the strings in reverse order
for (int i=v.size()-1; i>=0; --i)
cout << v[i] << '\n';
}
If you run the first program by itself, it will just print the 3 strings out. If you run the second program by itself, it will prompt the user for strings until he uses the termination command. But on all of the most widely used operating systems, you can chain the two together. Then the output of the first will become the input of the second. On Unix-like systems, you do it like this:
./output_program | ./input_program
On Windows, I think it's the same, or very similar. Not sure though.
The answer to your first question is no.
The answer to your second question is yes, but you need to specify the name of your entry point to your executable (via linker settings ... may not be available on all linker tools).
Below statement is wrong
See Ben's comment below. Useful info that.
Be aware that though the name of the entry-point can change, it MUST conform to the standard parameter and return types.

Infix equation solver c++ while loop stack

Im creating an infix problem solver and it crashes in the final while loop to finish the last part a of the equations.
I call a final while loop in main to solve whats left on the stack and it hangs there and if i pop the last element from the stack it will leave the loop and return the wrong answer.
//
//
//
//
//
#include <iostream>
#include<stack>
#include<string>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
using namespace std;
#define size 30
int count=0;
int count2=0;
int total=0;
stack< string > prob;
char equ[size];
char temp[10];
string oper;
string k;
char t[10];
int j=0;
char y;
int solve(int f,int s, char o)
{
cout<<"f="<<f<<endl;
cout<<"s="<<s<<endl;
cout<<"o="<<o<<endl;
int a;
if (o== '*')//checks the operand stack for operator
{
cout << f << "*" << s << endl;
a= f*s;
}
if (o == '/')//checks the operand stack for operator
{
cout << f << "/" << s << endl;
if(s==0)
{
cout<<"Cant divide by 0"<<endl;
}
else
a= f/s;
}
if (o == '+')//checks the operand stack for operator
{
cout << f << "+" << s << endl;
a= f+s;
}
if (o == '-')//checks the operand stack for operator
{
cout << f << "-" << s << endl;
a= f-s;
}
return a;
}
int covnum()
{
int l,c;
k=prob.top();
for(int i=0;k[i]!='\n';i++)t[i]=k[i];
return l=atoi(t);
}
char covchar()
{
k=prob.top();
for(int i=0;k[i]!='\n';i++)t[i]=k[i];
return t[0];
}
void tostring(int a)
{
stringstream out;
out << a;
oper = out.str();
}
void charstack(char op)
{
oper=op;
prob.push(oper);
}
void numstack(char n[])
{
oper=n;
prob.push(oper);
}
void setprob()
{
int f,s;
char o;
char t;
int a;
int i;
t=covchar();
if(ispunct(t))
{
if(t=='(')
{
prob.pop();
}
if(t==')')
{
prob.pop();
}
else if(t=='+'||'-')
{
y=t;
prob.pop();
}
else if(t=='/'||'*')
{
y=t;
prob.pop();
}
}
cout<<"y="<<y<<endl;
i=covnum();
cout<<"i="<<i<<endl;
s=i;
prob.pop();
t=covchar();
cout<<"t="<<t<<endl;
if(ispunct(t))
{
o=t;
prob.pop();
}
i=covnum();
cout<<"i="<<i<<endl;
f=i;
prob.pop();
t=covchar();
if (t=='('||')')
{
prob.pop();
}
a=solve(f,s, o);
tostring(a);
prob.push(oper);
cout<<"A="<<prob.top()<<endl;
}
void postfix()
{
int a=0;
char k;
for(int i=0;equ[i]!='\0';i++)
{
if(isdigit(equ[i]))//checks array for number
{
temp[count]=equ[i];
count++;
}
if(ispunct(equ[i]))//checks array for operator
{
if(count>0)//if the int input is done convert it to a string and push to stack
{
numstack(temp);
count=0;//resets the counter
}
if(equ[i]==')')//if char equals the ')' then set up and solve that bracket
{
setprob();
i++;//pushes i to the next thing in the array
total++;
}
while(equ[i]==')')//if char equals the ')' then set up and solve that bracket
{
i++;
}
if(isdigit(equ[i]))//checks array for number
{
temp[count]=equ[i];
count++;
}
if(ispunct(equ[i]))
{
if(equ[i]==')')//if char equals the ')' then set up and solve that bracket
{
i++;
}
charstack(equ[i]);
}
if(isdigit(equ[i]))//checks array for number
{
temp[count]=equ[i];
count++;
}
}
}
}
int main()
{
int a=0;
char o;
int c=0;
cout<<"Enter Equation: ";
cin>>equ;
postfix();
while(!prob.empty())
{
setprob();
a=covnum();
cout<<a<<" <=="<<endl;
prob.pop();
cout<<prob.top()<<"<top before c"<<endl;
c=covnum();
a=solve(c,a,y);
}
cout<<"Final Awnser"<<a<<endl;
system ("PAUSE");
return 0;
}
Hope this isn't too harsh but it appears like the code is riddled with various problems. I'm not going to attempt to address all of them but, for starters, your immediate crashes deal with accessing aggregates out of bounds.
Example:
for(int i=0;k[i]!='\n';i++)
k is an instance of std::string. std::string isn't null-terminated. It keeps track of the string's length, so you should be do something like this instead:
for(int i=0;i<k.size();i++)
Those are the more simple kind of errors, but I also see some errors in the overall logic. For example, your tokenizer (postfix function) does not handle the case where the last part of the expression is an operand. I'm not sure if that's an allowed condition, but it's something an infix solver should handle (and I recommend renaming this function to something like tokenize as it's really confusing to have a function called 'postfix' for an infix solver).
Most of all, my advice to you is to make some general changes to your approach.
Learn the debugger. Can't stress this enough. You should be testing your code as you're writing it and using the debugger to trace through it and make sure that state variables are correctly set.
Don't use any global variables to solve this problem. It might be tempting to avoid passing things around everywhere, but you're going to make it harder to do #1 and you're also limiting the generality of your solution. That small time you saved by not passing variables is easily going to cost you much more time if you get things wrong. You can also look into making a class which stores some of these things as member variables which you can avoid passing in the class methods, but especially for temporary states like 'equ' which you don't even need after you tokenize it, just pass it into the necessary tokenize function and do away with it.
initialize your variables as soon as you can (ideally when they are first defined). I see a lot of obsolete C-style practices where you're declaring all your variables at the top of a scope. Try to limit the scope in which you use variables, and that'll make your code safer and easier to get correct. It ties in with avoiding globals (#2).
Prefer alternatives to macros when you can, and when you can't, use BIG_UGLY_NAMES for them to distinguish them from everything else. Using #define to create a preprocessor definition for 'size' actually prevents the code above using the string's 'size' method from working. That can and should be a simple integral constant or, better yet, you can simply use std::string for 'equ' (aside from making it not a file scope global).
Prefer standard C++ library headers when you can. <ctype.h> should be <cctype>, <stdlib.h> should be <cstdlib>, and <stdio.h> should be <stdio>. Mixing non-standard headers with .h extension and standard headers in the same compilation unit can cause problems in some compilers and you'll also miss out on some important things like namespace scoping and function overloading.
Finally, take your time with the solution and put some care and love into it. I realize that it's homework and you're under a deadline, but you'll be facing even tougher deadlines in the real world where this kind of coding just won't be acceptable. Name your identifiers properly, format your code legibly, document what your functions do (not just how each line of code works which is something you actually shouldn't be doing so much later as you understand the language better). Some coding TLC will take you a long way. Really think about how to design solutions to a problem (if we're taking a procedural approach, decompose the problem into procedures as general units of work and not a mere chopped up version of your overall logic). #2 will help with this.
** Example: rather than a function named 'postfix' which works with some global input string and manipulates some global stack and partially evaluates the expression, make it accept an input string and return* the individual tokens. Now it's a general function you can reuse anywhere and you also reduced it to a much easier problem to solve and test. Document it and name it that way as well, focusing on the usage and what it accepts and returns. For instance:
// Tokenize an input string. Returns the individual tokens as
// a collection of strings.
std::vector<std::string> tokenize(const std::string& input);
This is purely an example and it may or may not be the best one for this particular problem, but if you take a proper approach to designing procedures, the end result is that you should have built yourself a library of well-tested, reusable code that you can use again and again to make all your future projects that much easier. You'll also make it easier to decompose complex problems into a number of simpler problems to solve which will make everything easier and the whole coding and testing process much smoother.
I see a number of things which all likely contribute to the issue of it not working:
There are no error or bounds checking. I realize that this is homework and as such may have specific requirements/specifications which eliminate the need for some checks, but you still need some to ensure you are correctly parsing the input. What if you exceed the array size of equ/tmp/t? What if your stack is empty when you try to pop/top it?
There are a few if statements that look like else if (t == '+' || '-') which most likely doesn't do what you want them to. This expression is actually always true since '-' is non-zero and is converted to a true value. You probably want else if (t == '+' || t == '-').
As far as I can tell you seem to skip parsing or adding '(' to the stack which should make it impossible for you to actually evaluate the expression properly.
You have a while loop in the middle of postfix() which skips multiple ')' but doesn't do anything.
Your code is very hard to follow. Properly naming variables and functions and eliminating most of the globals (you don't actually need most of them) would help a great deal as would proper indentation and add a few spaces in expressions.
There are other minor issues not particularily worth mentioning. For example the covchar() and covnum() functions are much more complex than needed.
I've written a few postfix parsers over the years and I can't really follow what you are trying to do, which isn't to say the way you're trying is impossible but I would suggest re-examining at the base logic needed to parse the expression, particularly nested levels of brackets.