Why this C++ code is not counting properly? - c++

I have written a code in c++ to count zeros. The input have to take as string. The input will be a digit with 1 and 0.
Example:
Input: 1000000001
Output: 8
The answer should be 8 but my code is showing 0. Where is the problem in the code.
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string players;
cin >> players;
int count = 0;
for (int j = 0; j < players.length(); j++)
{
if (players[j] == 0)
{
count++;
}
}
cout << count;
return 0;
}
Please help me to find and solve it.
Thank you.

you need to compare with char not int:
if (players[j] == '0')

if condition for players[j] == 0 is wrong, your input is string type while you are trying to compare with the integer type 0. The correct if check is players[j] == '0'. Using bits/stdc++.h and using namespace std; is a big no in C++.
#include <iostream>
#include <string>
int main()
{
std:: string players;
std:: cin >> players;
int count = 0;
for(const char &player : players)
{
if (player == '0')
{
count += 1;
}
}
std:: cout << count;
return 0;
}

the condition is wrong.
write code like
players[j] == "0"
your condition means that
player[j] == NULL

Related

Store and print characters but the output is not what is expected

I'm very new to C++. This code is supposed to store and print out every other number and stop when given the symbol #, but the output is weird. It outputs something like 0x6fdd90. Any help would be much appreciated.
#include <iostream>
#include <string>
using namespace std;
int main(){
string s[11];
int count = 1, wordlength = 0;
char a;
cin.get(a);
while (a != '#'){
if (wordlength == 10)
break;
if (count % 2 != 0){
s[wordlength] = a;
wordlength++;
}
cin.get(a);
count++;
}
s[wordlength] = '\0';
cout << s;
return 0;
}
cout << s;
Is printing the address of the 1st element in your array s.
You may want to loop through s to print all the elements.
for (int i =0; i < sizeof(s)/sizeof(s[0]); i++) {
cout<< s[i] << "\n";
}
It is better to user char array than string array for your purpose.

C++ How to find out most consecutive digits in an array?

Hi guys I'm trying to write a code where when i type a binary string I need to mind the most consecutive numbers of occurrence 1 has occurred. For example, if i type 00111001, it should be 3, 1100111011111, it should be 5 etc. This is my code so far.
int main () {
string s1;
cin >> s1;
int l1=s1.size()-1; // length-1 hence the for loop array doesnt go out of bounds
int max=0; // this tells us the max number of occurrence
int count=0;
for (int i=0;i<l1;i++) {
if (s1[i]=='1' && s1[i+1]=='1') { // if s[0] and s[1] are both 1, it adds 1
count++;}
if (count>0 && count>max)
{max=count; // storing the count value in max.
}
if (s1[i]=='0' || s1[i+1]=='0'){ //resetting count if it encounters 0
count=0;
}
}
max=max+1;
cout << max << '\n' << endl;
The issue is if I write 1111001 it runs (I get 4), but when i type 1100111001 I get 2. Don't get why there's ambiguity. Please let me know what I need to do
Thanks
I'd only increment the count in case of 1, and zero it when 0 is reached.
whenever count is bigger than max, assign count to max and that's it.
btw, I get 3 for the input 1100111001 with your program.
#include <iostream>
using namespace std;
int main() {
string s1;
cin >> s1;
int l1 = s1.size();
int max = 0;
int count = 0;
for (int i = 0; i < l1; i++)
{
if (s1[i] == '1')
{
count++;
}
else
{
count = 0;
}
if (count > max)
{
max = count;
}
}
cout << max << '\n' << endl;
}
Let's solve this using find, given string s1 which contains your input string you can just do:
auto max = 0;
for(auto start = find(cbegin(s1), cend(s1), '1'); start != cend(s1); start = find(start, cend(s1), '1')) {
const auto finish = find(start, cend(s1), '0');
const auto count = distance(start, finish);
if(count > max) {
max = count;
}
start = finish;
}
Live Example
I want to offer you such an option for calculating through tokens and sorting:
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string s1;
cin>>s1;
istringstream s(s1);
vector<string> result;
while (std::getline(s,s1,'0')) {
result.push_back(s1);
}
sort(result.begin(),result.end(),[](const string &a, const string &b){ return a.length()>b.length();});
cout << result.at(0).length() << endl;
return 0;
}

How to make a while loop till there is something to be readen c++

I know that you probably gona again vote me down, I really don't understand this but im really stuck at something and cant figure it out , there is no such information anywhere in the web , neither in my book for the course, so I have this assignment where I need make 2 sums of containers where the difference between 2 sums is the lowest , so the program is done is working perfectly calculated everything however , in my assignment:
The user enter on one row unkwonw length numbers so after that I do all kind of sums between them and find the one with lowest difference between.
Ok but the way I wrote the code I use one while(true) so that to work with infinity testcases(as from assignment) and in this while(true) I have another while(cin>>(SOMEINT)) loop and push it back in a vector , and after it reads new line it just break the wile and continue with the calculation.
However in our test software this one give runtime error since after finding some cases then it start print infinity 0 0 since there is nothing to enter but the while(true) just continues.
I mean I just want to make it that way that the while is till user enters something , for instance you enter 30 50 90 it will return 80 90 , then wiat for another entry and so on.
CODE:
#include <iostream>
#include <string>
#include<vector>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <climits>
using namespace std;
const int length = 17000;
int power(int x){
int sum =2;
for(int i = 0;i<x;i++) {
sum *= 2;
}
return sum;
}
bool ison(int i,int x)
{
if((i>>x) & 1)return true;
return false;
}
int main()
{
while(true){
vector<int> Vec;
int cur = 0;
while (cin >> cur) {
Vec.push_back(cur);
if (cin.get() == '\n') {
break;
}
}
int * sumOfarr1 = new int[length];
int * sumOfarr2 = new int[length];
for(int i = 0; i<length;i++){
sumOfarr1[i] = 0;
}
for(int i = 0; i<length;i++){
sumOfarr2[i] = 0;
}
int index=0;
for(int i=1;i<length;i++)
{
for(int j=0;j<Vec.size();j++)
{
if(ison(i,j))
{
sumOfarr1[index]+=Vec[j];
}
else
{
sumOfarr2[index]+=Vec[j];
}
}index++;
}
int ans=INT_MAX;
int ii;
for(int i=0;i<index;i++)
{
if(abs(sumOfarr1[i]-sumOfarr2[i])<ans)
{
ii=i;
ans=abs(sumOfarr1[i]-sumOfarr2[i]);
}
}
if(sumOfarr1[ii]<sumOfarr2[ii]){
cout << sumOfarr1[ii] << " " << sumOfarr2[ii];
}
else{
cout << sumOfarr2[ii] << " " << sumOfarr1[ii];
}
cout << endl;
delete[] sumOfarr1;
delete[] sumOfarr2;
Vec.clear();
}
return 0;
}
Yes I found the solution just using getline and stringstream.
aka this
vector<int> Vec;
string line;
while(getline( cin, line ))
{
istringstream iss( line );
int number;
while( iss >> number )
Vec.push_back(number);
}

Unknown error in code

Here's a link to the problem I am trying to solve: http://usaco.org/index.php?page=viewproblem2&cpid=187
Here's a link to the solution of the problem: http://usaco.org/current/data/sol_cowfind.html
Here's my solution that I wrote:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string n; int answer = 0;
ifstream fin("cowfind.in");
fin >> n;
fin.close();
int c = 0;
//process for finding the number of possible outputs
for(int i = 0; i < n.size(); i++)
{
if(n[i-1] == '(' && n[i] == '(') //increment the variable c for each pair of "hind" legs
c++;
if(n[i-1] == ')' && n[i] == ')') //increment answer for each pair of front legs
answer++;
}
answer = answer * c; //number of pairs of hind legs * number of pairs of front legs
ofstream fout("cowfind.out");
fout << answer;
fout.close();
return 0;
}
With that being said, what is wrong with my code? It keeps producing incorrect outputs, and I'm not sure why.
Your calculation is incorrect. Lets look at this input: ))((. There is no solution here but your code will produce 1 solution.
Try to iterate the string searching for the first literal ((. Once found - iterate the rest of the string to find )) and add them to the solution sum.
Good luck!

Error-correcting loop in C++, find specific chars in a string and flag as bad input

Here is v1.0 of the binary_to_decimal converter I wrote. I want to make several changes as I keep improving the spec. Classes and pointers will be added as well in the future. Just to keep me fresh and well practiced.
Well, I now want to implement an error-correcting loop that will flag any character that is not a 0 or a 1 and ask for input again.
I have been trying something along the line of this code block that worked with an array.
It might be way off but I think I can tweak it. I am still learning 0_0
I want to add something like this:
while ((cin >> strint).get())
{
cin.clear(); //reset the input
while (cin.get() != '\n') //clear all the way to the newline char
continue; //
cout << "Enter zeroes and/or ones only! \n";
}
Here is the final code without the error-correcting loop:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
const int MAX = 100;
int conv(int z[MAX], int l[MAX], int a);
int main()
{
int zelda[MAX];
int link[MAX];
string strint;
int am;
cout << "Enter a binary number: \n";
(cin >> strint).get(); //add error-correction to only read 0s and 1s.
am = strint.size();
cout << am << " digits entered." << endl;
int i = 0;
int p = 0;
while (i < am)
{
zelda[i] = strint[p] - '0'; //copies the string array elements into the int array; essentially STRING TO INT (the minus FORCES a conversion because it is arithmetic) <---- EXTREMELY CLEVER!
++i;
++p;
}
cout << conv(zelda, link, am);
cin.get();
return 0;
}
int conv(int zelda[MAX], int link[MAX], int length)
{
int sum = 0;
for (int t = 0; t < length; t++)
{
long int h, i;
for (int h = length - 1, i = 0; h >= 0; --h, ++i)
if (zelda[t] == 1)
link[h] = pow(2.0, i);
else
link[h] = 0;
sum += link[t];
}
return sum;
}
thanks guys.
I'm not completely sure of what you're trying to do, but I think what you're wanting is string::find_first_not_of. There's an example included in that link. You could have something like: myString.find_first_not_of("01");
If the return value is string::npos, then there are no characters in the string other than 1 or 0, therefore it's valid. If the return value is anything else, then prompt again for valid input and continue looping until the input's valid.