How to stop recursion if nothing is inputed in cin?
I am writing a program that must print numbers at first which was entered at last.
So here is my code:
#include <iostream>
using namespace std;
void recursive()
{
long long n;
if((cin>>n)&&(!cin.eof())) // Dont work because enter is ignored in cmd window os
recursive();
cout<<n<<endl;
return;
}
int main()
{
recur开发者_JAVA百科sive();
return 0;
}
Any idea how to stop function when nothing is input? Or how to solve problem in another way?
Thanks
As your program is right now it will read the long long's until cin's operator void* indicates that the value read was not compatible (but still prints the n , filled with garbage,that it failed to read), as you notice it ignores the blank lines.
If I understand correctly, what you want is that when the user inputs a blank line the program should output the numbers read, a simple way to do this would be to read the input as a string, then check the string's length, and use a stringstream to convert it to the appropriate type.
#include <iostream>
#include <sstream>
#include <string>
void recursive()
{
std::string input;
long long n;
if ( std::getline(std::cin,input) && input.length() > 0 )
{
std::istringstream ss(input);
if (ss >> n)
{
recursive();
std::cout << n << std::endl;
}
}
}
int main ()
{
recursive();
return 0;
}
edit
Here's another way, if your input comes in the form 46 798 4163 4654 32132
, it uses std::cin.peek() that returns the next character in the input without extracting it, the result of peek() is compared to '\n' to test if the user pressed enter, and if that's the case it prints the number it just read without waiting for the next number
#include <iostream>
#include <sstream>
#include <string>
void recursive_in_a_line ()
{
long long n;
if (std::cin >> n)
{
if (std::cin.peek() != '\n')
{
recursive();
}
std::cout<< n << std::endl;
}
}
int main ()
{
recursive_in_a_line();
return 0;
}
Do you have to implement the program in a recursive way? An alternative solution that does not use recursion would be to read the numbers in a while loop and add them to a container (a list or a vector), then display the content of the container.
精彩评论