Can't stop reading lines in c++ - c++

The following code is for a homework assignment due on 17 October. The problem states to "write a program with a loop that lets the user enter a series of numbers. After all the numbers have been entered, the program should display the largest and smallest numbers entered."
#include "stdafx.h"
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
bool isNumeric(string aString)
{
double n;
istringstream is;
cin >> aString;
is.str(aString);
is >> n;
if (is.fail())
{
return false;
}
return true;
}
vector<double> limits(vector<double> a)
{
// Returns [min, max] of an array of numbers; has
// to be done using std::vectors since functions
// cannot return arrays.
vector<double> res;
double mn = a[0];
double mx = a[0];
for (unsigned int i = 0; i < a.size(); ++i)
{
if (mn > a[i])
{
mn = a[i];
}
if (mx < a[i])
{
mx = a[i];
}
}
res.push_back(mn);
res.push_back(mx);
return res;
}
int main()
{
string line = " ";
vector<string> lines;
vector<double> arr;
cout << "Enter your numbers: " << endl;
while (!line.empty() && isNumeric(line))
{
getline(cin >> ws, line);
if (line.empty() || !isNumeric(line))
{
break;
}
lines.push_back(line);
transform(line.begin(), line.end(), line.begin(), [](char32_t ch) {
return (ch == ' ' ? '\000' : ch);
}); // Remove all spaces
arr.push_back(atof(line.c_str()));
}
vector<double> l = limits(arr);
cout << "\nMinimum: " << l[0] << "\nMaximum: " << l[1] << endl;
return 0;
}
The above code is what I have. However, it's not always outputting the correct maximum value and only outputs "0" for the minimum value. I can't seem to find what's wrong with this so if anyone could help that would be great.

For the minimum, your problem appears to be with the fact that in your limits() function, you initialize the value of min to 0. So if you have an array of [1, 2, 3, 4], it will check each element and, seeing that none of them is less than 0, leave 0 as the minimum. To fix this, you can set the initial value of mn to the first element of the array. Note that you will have to check to make sure the array has at least one element to avoid a possible overflow error.
For the maximum, I'm not sure what kind of inconsistencies you're having, but if your array only contained negative values, you would have the same problem as with minimum, where the initial value is higher than any of the actual values.

Related

delete all digits except one

I have this integer:
4732891432890432432094732089174839207894362154
It's big so I want to delete all digits in it except the digit 4 and I don't know how. This is my code:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
unsigned ll n, lastDigit, count = 0;
ll t;
cin >> t;
while(t--)
{
cin >> n;
while (n !=0)
{
lastDigit = n % 10;
if(lastDigit == 4)
count++;
n /= 10;
}
cout << count << "\n";
}
return 0;
}
I used the while loop because I have multiple test case not only that number.
Just to show you current C++ (C++20) works a bit different then wat most (older) C++ material teaches you.
#include <algorithm>
#include <iostream>
#include <string>
#include <ranges>
bool is_not_four(const char digit)
{
return digit != '4';
}
int main()
{
// such a big number iwll not fit in any of the integer types
// needs to be stored in memory
std::string big_number{ "4732891432890432432094732089174839207894362154" };
// or input big_number from std::cin
// std::cout >> "input number : "
// std::cin >> big_number;
// NEVER trust user input
if (!std::any_of(big_number.begin(), big_number.end(), std::isdigit))
{
std::cout << "input should only contain digits";
}
else
{
// only loop over characters not equal to 4
for (const char digit : big_number | std::views::filter(is_not_four))
{
std::cout << digit;
}
// you can also remove characters with std::remove_if
}
return 0;
}

numeric palindrome with leading zeros c++

I wanted to solve a problem, yet my code passes only 8 out of 10 tests. The problem is to determine whether a number 1<=N<=10^9 can be a numeric polyndrome. The thing is, you may add as many leading zeros as it requires to make a non-polyndrome into a polyndrome. If it is possible, or a number is polyndrome, the result must be yes, otehrwise no. For example, 2020 is not a polyndrome, but If I add a leading zero, it becomes 02020, which is a polyndrome. One main problem of my code is that i don't know the number of leading zeros needed to make a number a polyndrome. Here's my code:
#include <cstdio>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string N, N2;
cin >> N;
N2 = N;
reverse(N.begin(), N.end());
if (N2 == N) {
cout << "Yes" << "\n";
return 0;
}
else {
N2 = "0" + N2;
N = N + "0";
if (N != N2) {
cout << "No" << "\n";
return 0;
}
else {
cout << "Yes";
return 0;
}
}
}
I would be grateful for any help to enhance my code!
edit: I have to add leading zeros if it can turn a number into a polyndrome, that's the main thing
I would do something like:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
string n;
cin>>n;
string m =n;
reverse(n.begin(),n.end());
if(n==m){
cout<<"Yes"<<endl;
return 0;
}
int count=0;
int k=m.length();
for(int i=1; i<=k;i++){
if(m[i]=='0'){
count+=1;
}
}
for(int i=1;i<=count;i++){
m='0'+m;
}
string m2=m;
reverse(m.begin(), m.end());
if (m2 == m)
{
cout << "Yes" << endl;
return 0;
}
else{
cout << "No" << endl;
return 0;
}
}
Just to be complete, I will show you the answer based on the comments.
It is the same, if you add 0es to the beginning or remove them from the end.
If you have 2020, you can either add one leading 0 --> 02020 or remove a trailing 0 -> 202. Result is the same.
So, the algorithm will be.
Search from the right end for the first character that is not '0'
Build a pair forward and a pair reverse iterators, based on the iterator, found by `std::find
Compare temporary created strings, build from forward and reverse iterators
Output comparison result
Very simple example code:
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main() {
if (std::string numberAsString{}; std::cin >> numberAsString) {
std::string::reverse_iterator newEnd = std::find_if(numberAsString.rbegin(), numberAsString.rend(), [](const char c) {return c != '0'; });
std::cout << (std::string(numberAsString.begin(), newEnd.base()) == std::string(newEnd, numberAsString.rend()) ? "Yes\n" : "No\n");
}
}
I only changed in main else part of your code.
1. Now understand if some numerical string is not palindrome and you are going to make it palindrome by adding leading 0's then it must end with 0's.
For Ex. 100 is not palindrome but you can make it by 00100 it possible because two 0's present at end.
same with 10 -> 010
2. some numbers which are ends with 0's and not palindromes but we can make them by adding leading 0's
10, 20, 30.....90 -> (respective palindrome) 010,020,.....090
100, 110, 200, 220,.....900, 990 -> (respective palindrome) 00100, 0110, 00200, 0220.....00900, 0990
3. some numbers which are ends with 0's and not palindromes and we can't make them by adding leading 0's
120, 130...190
210, 230, 240,....290
.
.
.
11010
4.
Now if you see carefully the numbers which we can make palindrome you get that to be able to do so we have to add exact number of 0's at starting as present at the end. if you pause for minute and think then you get logical sense too.
5.
Now I am creating condition to right code on above analysis. I will talk about just else part
i> So I will check first that how many 0's present at end of number(while loop). at least one 0's must be present.
ii> Then I am adding as many leading 0's present at end.( for loop).
iii> Then storing N2 in N3 so I can reverse and check palindrome become or not because all numbers end with 0's do not become palindromes.
Code
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
int main()
{
string N, N2;
cin >> N;
N2 = N;
reverse(N.begin(), N.end());
cout<<N<<" "<<N2<<"\n";
if (N2 == N)
{
cout << "Yes" << "\n";
return 0;
}
else
{
int k=N2.length(), count=0, i=1;
while(N2[k-i]=='0')
{
count++;
i++;
}
if(count==0)
{
cout<<"No";
return 0;
}
for(int i=1; i<=count; i++)
{
N2="0" + N2;
}
string N3=N2;
reverse(N2.begin(), N2.end());
cout<<N3<<" "<<N2<<"\n";
if (N3 != N2)
{
cout << "No" << "\n";
return 0;
}
else
{
cout << "Yes";
return 0;
}
}
}
Also just note that you added <cstdio> two times even it didn't required one time also. Sometime if you include same header file twice it might cause error. Also there is no requirement of <cmath> library file. By the way you didn't include <string> library file might be in some cases your program run quite well without including it but it is not standard practise.

Subtract each elements of an array consecutively

I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5.
But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size.
Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on.
The problem is, how do I subtract them? I have two options:
The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on.
I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input.
Question: How do you solve this problem?
(This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?)
Thanks.
Let's see my code below of how I insert the user input into the array.
string input[100];
int arrayInput[100];
int x = 0;
for (int i = 0; i >= 0; i++) //which this will run until the user input 'count'
{
cout << "Number " << i+1 << ": ";
cin >> input[i];
arrayInput[i] = atoi(input[i].c_str());
...
//code to subtract them, and final answer will be in int x
...
if (input[i] == "count")
{
cout << "Result: " << x << endl;
}
}
You can/should use a dynamic sized container like std::vector as shown below:
#include <iostream>
#include <vector>
int main()
{
int n = 0;
//ask user how many input he/she wants to give
std::cout << "How many elements do you want to enter: ";
std::cin >> n;
std::vector<int> vec(n); //create a vector of size n
int resultOfSubtraction = 0;
//take input from user
for(int i = 0 ; i < n ; ++i)
{
std::cin >> vec.at(i);
if(i != 0)
{
resultOfSubtraction-= vec.at(i);
}
else
{
resultOfSubtraction = vec.at(i);
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Execute the program here.
If you want a string to end the loop then you can use:
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> vec;
int resultOfSubtraction = 0, i = 0;
std::string endLoopString = "count";
std::string inputString;
int number = 0;
//take input from user
while((std::getline(std::cin, inputString)) && (inputString!=endLoopString))
{
std::istringstream ss(inputString);
if(ss >> number)
{
vec.push_back(number);
if(i == 0)
{
resultOfSubtraction = number;
}
else
{
resultOfSubtraction-= number;
}
++i;
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}

Finding a Pair of character in a string [duplicate]

This question already has answers here:
Counting the number of occurrences of a string within a string
(5 answers)
Closed 2 years ago.
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int count = 0;
vector<string> v;
string resp;
cin >> resp;
v.push_back(resp);
for(int i = 0; i < v.size(); i++){
if(find(v.begin(), v.end(), "xy") != v.end()){
count++;
}
cout << count << endl;
}
return 0;
}
I want to find the character "xy" in the string for multiple test cases.
For input xy, my count value outputs correctly as 1.
But for the input xyxxy instead of 2 it gives the value as 0
It is only finding the value once but i want to check the count of xy in whole string
I tried to use the substring function as well but it failed to work
I don't get the idea of while loop but that worked for me.
#include <iostream>
#include <vector>
int main()
{
std::string str;
std::cin >> str;
int count = 0;
for (int i(0); i < str.size()-1; ++i)
{
if ((str[i] == 'x') && (str[i + 1] == 'y'))
{
++count;
}
}
std::cout << count;
}
You're looking for "xy" within a vector of strings, which in your example, has a single element, "xyxxy". Since "xy" is not equal to "xyxxy", you're not finding any matches.
But even if you tried to std::find "xy" within "xyxxy" itself - that would fail too, since std::find looks for a single element within a range (or rather, iterator pair).
Instead, you can use the string::find() method, as described here; or, as the case may be, std::string_view::find():
#include <string>
#include <vector>
#include <iostream>
#include <string_view>
int main() {
const std::string needle{"xy"};
std::string haystack;
std::cin >> haystack;
std::size_t count{0};
std::string_view remainder{haystack};
while(true) {
auto first_pos = remainder.find(needle);
if (first_pos == std::string_view::npos) { break; }
count++;
remainder = remainder.substr(first_pos+needle.length());
}
std::cout << "Found " << count << " occurrences of \"" << needle << "\"\n";
}
Note: This does not account for overlapping occurrences. If you want those, you could either always increase the starting position by just 1; or make your solution more complex by employing something Boyer-Moore or Knuth-Morris-Pratt search (see String search algorithms), and resuming it at the correct state after each occurrence found.

Non-repeating random numbers

I'm working on a synonym puzzle, it gives you a word and wants you to find the synonym of it given the lenght of the word. Everything works fine, but it happens on an ordered sequence; words do not appear randomly. I need knumber of non-repeating random numbers for that. Here's my code:
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
const int k=4;
string word[k]={"furious","tiny","untrue", "humorous", "harm"};
string nword[k]={"angry","small","false", "funny", "damage"};
string j;
int point, p = 0;
int ctr=0;
srand(time(NULL));
int randNum = (rand() % k) + 0;
for(int i=0; i<k; i++)
{
cout << nword[i] << "\n";
cout << "The length of the word: " << word[i].length() << "\n";
cin>>j;
ctr++;
if(j==word[i])
{
cout<<"Correct! Score: " << i+1 << " point." << "\n\n";
}
else
{
cout<<"Wrong"<<endl;
}
}
return 0;
}
As you can see, the variable randNum holds the value of the random number from 0 to k, (k is 4, combined with 0, I got 5 words). In for loop, when I set the nword and word like nword[randNum], and word[randNum], the result leaves a lot to be desired. First, I think there's no sync for the two (nword and word). It will apply different random numbers for the two (I might be wrong) and the second, it will be repetitive. As seen, the execution is score-based and completable, so I need non repeating questions until it reaches to k.
You could shuffle your word arrays by using the Durstenfeld shuffle:
for(int i=k-1; i>0; i--)
{
int j = rand() % (i+1)
string temp = word[i];
word[i] = word[j];
word[j] = temp;
temp = nword[i];
nword[i] = nword[j];
nword[j] = temp;
}
As pointed out by WhozCraig, an alternative option (arguably better, as it doesn't require permuting multiple arrays), is to create an array with indices 0..(k-1) and shuffle this array instead. This array would then contain a set of randomised indices which could be used to iterate over your word arrays.
#include <iostream>
#include <algorithm>
#include <string>
#include <random>
#include <numeric>
using namespace std;
int main()
{
static const size_t k=5;
string word[k]={"furious","tiny","untrue", "humorous", "harm"};
string nword[k]={"angry","small","false", "funny", "damage"};
int ctr=0;
// build prng
std::random_device rd;
std::mt19937 rng(rd());
// build index sequence, then shuffle
size_t idx[k];
std::iota(std::begin(idx), std::end(idx), 0);
std::shuffle(std::begin(idx), std::end(idx), rng);
for(auto i : idx)
{
std::string s;
cout << nword[i] << "\n";
cout << "The length of the word: " << word[i].length() << "\n";
if (!(cin>>s))
break;
if(s==word[i])
{
cout<<"Correct! ";
++ctr;
}
else
{
cout<<"Wrong. ";
}
std::cout << "Score: " << ctr << " point(s).\n\n";
}
return 0;
}