How to Exit program loop on pressing Enter/Return Key in C++? - c++

The Challenge is Given like this:
You are provided with an unknown number of test cases. Each test case consists of a natural number, which is followed by a white space, relational operator (==, !=, >= or <=), white space, and another natural number. All test cases are separated with a new line character. You can assume that no number has more than 1000 digits.
So, I'm trying to solve the above problem using C++.The problem is, this program should run for any number of cases that will be checked by Online Judge but my code is works for a limited number of inputs only, as the code will going to be checked by online judge and number of inputs is not specified. So I stuck how to solve this problem.I also tried using do..while() loop and while() loop but it doesn't work -_-
My code is given below:
#include <iostream>
using namespace std;
bool isSmaller(int n1, int n2, string oper)
{
// Calculate lengths of both string
if (oper == "==")
/* code */
if (n1 == n2)
return true;
if (oper == "<=")
/* code */
if (n1 <= n2)
return true;
if (oper == ">=")
/* code */
if (n1 >= n2)
return true;
if (oper == "!=")
/* code */
if (n1 != n2)
return true;
return false;
};
int main() {
/* code */
int n1, n2;
string oper;
for (int i = 0; i < 1; i++) {
cin >>n1>>oper>>n2;
}
for (int j = 0; j < 1; j++) {
if(isSmaller(n1, n2, oper)){
std::cout <<1<<'\n';
}
else{
std::cout <<0<< '\n';
}
}
return 0;
}
Ideal OUTPUT:
A binary sequence should appear on the output. ith element of the sequence should be equal to 1 or 0, depending on whether the corresponding relation is true or false. All elements of the sequence should be separated with a new line character.
Example
Input:
100 == 200
200 <= 100
200 >= 100
Output:
0
0
1

Here scanf() will help you to take unknown number of inputs.
You can include or to use scanf() and printf() in your C++ program.
while(scanf("%d %s %d",&n1,oper,&n2) == 3)
{
//Your code goes here.
}
Explanation
This works because scanf() returns the total number of inputs scanned successfully, or EOF if input failure occurs before the first receiving argument was assigned.
And in this case it will return 3 as for a successful scanning of n1, oper and n2.

finally I wrote the code based on the hint given by #bruno but still online judge returns an error I don't know wheres the problem but the code seems correct.
The Code is Below:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <list>
using namespace std;
bool computeResult(string line)
{
// compare two values from given operator
istringstream stream(line);
int n1, n2;
string oper;
stream >> n1 >> oper >> n2;
stream >> std::cout.rdbuf();
if (oper == "==")
return (n1 == n2);
if (oper == "!=")
return (n1 != n2);
if (oper == ">=")
return (n1 >= n2);
if (oper == "<=")
return (n1 <= n2);
return false;
};
int main() {
/* code */
list<bool> result;
std::string line;
std::istringstream stream(line);
cout << "Enter Numbers \n";
std::getline(std::cin, line);
do {
result.push_back(computeResult(line));
} while(std::getline(std::cin, line) && !line.empty());
for (auto b : result)
std::cout << b << std::endl;
return 0;
}

Related

The Coursera autograder gives me Unknown Signal 11

I'm in a class in Algorithms and now we are taking Greedy Algorithms.
Two of my solutions output "Uknown Signal 11" on some of the test cases.
However, I drove my program to the limit with the largest inputs possible.
It works just fine on my PC. However on Coursera's grader, it throws tgghis cryptic message of Unknown Signal 11.
Will this go away if I change to Python for example?
Here's the first code exhibiting the problem:
#include <iostream>
#include <utility>
#include <algorithm>
using namespace std;
bool sortAlg(pair<double, pair<uint64_t,uint64_t>> item1, pair<double,
pair<uint64_t,uint64_t>> item2)
{
return (item1.first >= item2.first);
}
int main()
{
uint64_t n, index = 0;
double W, val;
cin >> n >> W;
pair<double, pair<uint64_t,uint64_t>> items[n];
for (int i=0; i <n; i++)
{
cin >> items[i].second.first >> items[i].second.second;
items[i].first = (double)items[i].second.first / (double)items[i].second.second;
}
sort(items,items+n, sortAlg);
while(W > 0 && n > 0)
{
if (items[index].second.second <= W)
{
val += items[index].second.first;
W -= items[index].second.second;
index++;
n--;
}
else
{
val += items[index].first * W;
W = 0;
index++;
n--;
}
}
printf("%.4f",val);
return 0;
}
I think this has to do with the while loop, but I can't think of anything where the program will make an out of bounds array call using index.
Anyways it is a fractional knapsack implementation.
Here's the second code which also gives unknown signal 11:
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
#include <utility>
using namespace std;
bool sortAlg(string num1, string num2)
{
if (num1[0] > num2[0]) return true;
else if (num1[0] < num2[0]) return false;
else
{
if (num1.size() == 1 && (num1[0] > num2[1])) return true;
else if (num1.size() == 1 && (num1[0] < num2[1])) return false;
else if (num2.size() == 1 && (num1[1] > num2[0])) return true;
else if (num2.size() == 1 && (num1[1] < num2[0])) return false;
else if (num1 == "1000" || num2 == "1000") return (num1 < num2);
else
{
if (num1.size() == num2.size()) return (num1 > num2);
else
{
return (num1[1] > num2[1]);
}
}
}
}
int main()
{
string num;
int n, n2 = 1;
cin >> n;
//int numbers[n];
vector<string> numbers2;
for (int i =0; i <n; i++)
{
num = to_string(n2);
cout << num << endl;
numbers2.push_back(num);
n2 += 10;
}
sort(numbers2.begin(), numbers2.end(), sortAlg);
for (auto number : numbers2)
{
cout << number;
}
return 0;
}
I suspect the sortAlg function used in sort function, but on my PC it is relatively fast. And the problem statement required some weird sorting.
The problem was given a set of numbers, arrange them to make thebiggest number possible.
If given 9, 98, 2, 23, 21 for example it should give me 99823221.
(9 > 98 > 23 > 2 > 21)
So I sort by the first digit then the next and so on.
You have a StackOverflow error.
The necessary stack size depends on the depth of your recursion, the number of parameters of your recursive function and on the number of local variables inside each recursive call.
In Python, you have to set the necessary stack size. The starter files provided in Python 3 would have the sample below:
import threading
sys.setrecursionlimit(10 ** 6) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
...
threading.Thread(target=main).start()
Note how the stack_size is allocated.
It's just an additional information related to Coursera grader.
In the week 6 the same course , if you declare a 2D array for the dynamic programming problem, the grader gives the Signal 11 error and program fails even if it is working perfectly fine on local machine .
Solution to above problem - replace 2-D array by 2D vector (in case of C++) and submit again. The grader will accept the code solution and no signal 11 error will be thrown.

Programming a boolean program using recursion

I have this homework to do and I dont really understand why my program doesnt really work(prints 1 constantly).
I am supposed create a program that receives a number and a digit from the user(we can assume that the input is ok)
and it prints 1 in case the digit appears inside the number even times. In case it appears odd amount of times it will print 0.
I have to use a boolean recursion function.
can someone please tell me whats wrong with it?
#include <iostream>
using namespace std;
bool isEven(int num, int dig);
void main()
{
bool res;
int num, dig;
cout << "Please enter a number and a digit" << endl;
cin >> num >> dig;
cout << isEven(num, dig);
}
bool isEven(int num, int dig)
{
bool res;
int counter = 0;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig);
if (num % 10 == dig)
counter++;
return res;
}
}
You're not passing the value of your counter down through your recursive calls - it's effectively unused in your current implementation.
You're also missing one check if dig % 10 == num - in your code, you never check the last digit of the number.
bool isEven(int num, int dig, int counter)
{
bool res;
if (num % 10 == dig)
counter++;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig, counter);
return res;
}
}
And you can just call it with isEven(num, dig, 0) or create a wrapper function that takes just num and dig and calls this version with 0.
Note that there's a (imo) more elegant recursive expression of this function without using counters, although it's got some slightly unintuitive bits to it:
bool isEven(int num, int dig)
{
// Base case, single digit
// If num % 10 == dig on this last digit, we've got 1 match (odd, so return false)
if (num < 10)
return num % 10 != dig;
bool result = isEven(num / 10, dig);
if (num % 10 == dig) // This digit matches, count one more/flip the result
result = !result;
return result;
}

Print all prime number lower than n in C++ ( file crash )

I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.
You want to print all prime numbers less than n and has a function to check primality already.
Just
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
And while printing, add a some character to separate the numbers inorder to be able to distinguish them like
cout<<i<<endl;
P.S: I think you call this a C++ program. Not a script.
Edit: This might interest you.

Anagram Program Testing

My anagram program works great in my dev-cpp but in any online tester throw wrong answer on any testing anagram. Can someone help me?
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char input1[10000];
char input2[10000];
cin >> input1;
getchar();
cin >> input2;
getchar();
int leng;
leng = strlen(input1);
bool output[leng];
for(int i=0; i<leng; i++){
for(int y=0; y<leng; y++){
if( input1[i] == input2[y] ){
output[i] = true;
}
}
}
for(int o=0; o<leng; o++ ){
if( (o+1) == leng){
if( output[o] == true){
cout << "ano" << endl;
break;
}
}else if(output[o] == true) {
continue;
}
cout << "nie" << endl;
break;
}
getchar();
return 0;
}
Rather than trying to reinvent the wheel, there is a neat function is_permutation in <algorithm> that can make this problem trivial . .
#include <algorithm>
bool isAnagram(std::string a, std::string b) {
if(a.size() == b.size()) {
return std::is_permutation ( a.begin(), a.end(), b.begin(), [](char x, char y){return std::tolower(x) == std::tolower(y);} );
}
return false;
}
Just remove the binary predictate if you want case sensitivity. Try it here
You have issue with your algorithm. Imagine the following scenario:
Input1: ab
Input2: cdefab
Your algorithm will return OK because it will only check that a & b characters of input1 are present in input2.
Same problem with example such as:
Input1: aaaaaa
Input2: a
Or:
Input1: aaaab
Input2: bbbba
You can change your algorithm by:
Counting characters using an array of 256 (index of your character in ASCII) int initialized to 0. Increment for input1 and decrement for input2, in the end your array should be filled with 0. O(n) algo
Sorting your two inputs and comparing them character after character. O(n^2) algo
You can find more details about those algo here.

Input String where Integer should be - C++

I'm a beginner and am stuck on such a simple problem whilst working through Stroustrup's Principles and Practices.
Using only basic elements
#include "std_lib_facilities.h"
int main()
{
double highest = 0;
double lowest = 100;
int i=0;
double sum = 0;
vector <double> inputlist;
double input;
string unit;
cout<<"Type in a number followed by it's unit \n";
while(cin>>input>>unit){
inputlist.push_back(input);
sum += inputlist[i];
if (input >= lowest && input <= highest){
cout<<input<<" \n";
++i;
}
else if (input < lowest){
lowest = input;
cout<<"\nLowest Number so far \n"<<lowest;
++i;
}
else if (input > highest){
highest = input;
cout<<"\nHighest number so far \n"<< highest;
++i;
}
else
cout<<"Lowest is: \n"<<lowest<<"\n\n Highest is: \n"<<highest<<" \n\n and the total is: \n"<<sum;
if (unit == "ft", "m", "in","cm")
cout<<unit<<"\n";
else
cout<<"cannot recognize unit";
}
keep_window_open();
return 0;
}
I need the program to show the user the sum and highest and lowest value when the character "|" is entered. Problem is: i need this entered where the Integer value should be entered.
NOTE: I don't know much about conversions but tried a few and they didn't work.
If I understood you correctly, you want to read int from std::cin, but:
int i;
if (std::cin >> i) {
...
doesn't suite your needs since there might be '|' sign as a signal for termination of reading.
Here's what you could do: read input word by word (std::string) and parse these words separately using temporary std::istringstream:
std::string word;
if (std::cin >> word) {
if (word == "|")
...
// else:
std::istringstream is(word);
int i;
if (is >> i) {
// integer successfully retrieved from stream
}
}
just #include <sstream>
Read the value with string. if it doesn't match | convert it to double using the following function:
double toDouble(string s)
{
int sign = 1, i=0;
if (s[0]=='-')
sign = -1, i=1;
double result = 0, result2 = 0;
for (; i < s.size(); i++)
if (s[i] == '.')
break;
else
result = result * 10 + (s[i] - '0');
for (i = s.size()-1 ; i>=0 ; i--)
if (s[i] == '.')
break;
else
result2 = result2 / 10 + (s[i] - '0');
if (i>=0)
result += result2/10;
return result * sign;
}
Summing meters with inches does not make much sense. Therefore, you should consider to translate the units into scaling factors. You could use a map to get the scaling factors.
Even if this is somewhat overshoot you might use regular expressions to parse the user input. If the regex does not match you can test for stuff like "|".
In the new c++-standard (http://en.wikipedia.org/wiki/C%2B%2B11) a regex library is defined for this purpose. Pityingly, the g++ regex library is buggy. But you can use boost (http://www.boost.org/doc/libs/1_54_0/libs/regex/doc/html/boost_regex/).
Here is an example:
#include <iostream>
#include <vector>
#include <map>
#include <boost/regex.hpp> //< Pittyingly std::regex is buggy.
using namespace std; ///< Avoid this in larger projects!
using namespace boost;
int main() {
const string strReFloat("([-+]?[[:digit:]]*\\.?[[:digit:]]+(?:[eE][-+]?[[:digit:]]+)?)");
const string strReUnit("([[:alpha:]]+)");
const string strReMaybeBlanks("[[:blank:]]*");
const string strReFloatWithUnit(strReMaybeBlanks+strReFloat+strReMaybeBlanks+strReUnit+strReMaybeBlanks);
const regex reFloatWithUnit(strReFloatWithUnit);
const map<const string,double> unitVal= {
{"m", 1.0},
{"in", 0.0254},
{"ft", 0.3048},
{"cm", 0.01}
};
double highest = 0;
double lowest = 100;
int i=0;
double sum = 0;
vector <double> inputlist;
double input;
double unitToMeter;
string unit;
string str;
while( (cout<<"\nType in a number followed by it's unit \n", getline(cin,str), str != "") ){
smatch parts;
if( regex_match(str,parts,reFloatWithUnit) ) {
unit = parts[2].str();
auto found = unitVal.find(unit);
if( found != unitVal.end() ) {
cout<<unit<<"\n";
input = found->second * atof(parts[1].str().c_str());
} else {
cout << "Unit \"" << unit << "\" not recognized. Using meters.\n";
}
inputlist.push_back(input);
sum += inputlist[i];
if (input >= lowest && input <= highest){
cout<<input<<" \n";
++i;
}
else if (input < lowest){
lowest = input;
cout<<"\nLowest Number so far \n"<<lowest;
++i;
}
else if (input > highest){
highest = input;
cout<<"\nHighest number so far \n"<< highest;
++i;
}
} else if( str == "|" ) {
cout << "sum:" << sum << "\n";
} else {
cout << "Input not recognized.\n";
}
}
return 0;
}