I have an array with a particular size (100 for example), which is filled with user input. However, the user might not necessarily enter enough data to fill the entire array.
I want to count the elements of the array which the user entered. How can I do this?
I tried by this for loop:
int COUNT=0;
for( int i=0; i<size; i++)
if (Student[i]=1) //which means this element is true, not empty element.
COUNT++;
cout<< COUNT+1 << "
";
But this code gives an error on this line:
if (Students[i]==1)
Also, if the user enters repeated elements, I just want to count the unique elements (count each value one time).
My code is:
#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
#define size 100
using namespace std;
int main()
{
string Students_;
string word2;
getline(cin, Students_);
int k;
int l;
k = Students_.find("[");
Students_.erase(0, k + 1);
l = Students_.find("]");
string line2 = Students_.erase(l);
stringstream iss(line2);
string Students[size];
int counter = 0;
while (getline(iss, word2, ';') && counter < size) {
Students[counter++] = word2;
}
int COUNT = 0;
for (int i = 0; i < size; i++)
if (Students[i] == 1)
COUNT++;
cout << COUNT + 1 << "
";
return 0;
}
The input for example is:
Students=[8347,Islam Said,(ARC135,ARC114,ARC134,ARC135);8256,Esraa Said,(ARC134,ARC135,ARC114);8336,Ismail Said,(ARC134,ARC135,ARC114);8285,Ismail Adballah,(ARC114,ARC135,ARC134,ARC114);8349,Esraa Kassem,(ARC135,ARC114,ARC134);8505,Bassant Kassem,(ARC114,ARC135,ARC134,ARC114);8381,Ismail Kassem,(ARC135,ARC134,ARC114,ARC135);8360,Bassant AbdAlrahman,(ARC114);8498,Mohamed Kamal,(ARC135,ARC114,ARC134);8255,Ali Bassem,(ARC114,ARC135);8437,Mohamed Said,(ARC135);8524,Osama Adballah,(ARC114,ARC135);8334,Osama Kamal,(ARC114,ARC135,ARC134);8501,Esraa Tarek,(ARC135,ARC134);8394,Ahmed Zain,(ARC134,ARC135)]
The input is not constant, it's just an example.
See Question&Answers more detail:
os