如何计算在C数组的元素++

问题描述 投票:-5回答:2

我有具有特定大小(100为例),其填充有用户输入阵列。然而,用户不一定输入足够的数据来填充整个数组。

我想算哪个用户输入的数组中的元素。我怎样才能做到这一点?

我试图通过这个for循环:

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 << "\n";

但是这个代码给出了此行的错误:

if (Students[i]==1)

另外,如果用户输入重复的元素,我只是想算的独特元素(一个时间计算每个值)。

我的代码是:

#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 << "\n";
    return 0;
}

例如输入是:

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)]

输入是不是恒定的,它只是一个例子。

c++ arrays loops if-statement for-loop
2个回答
0
投票

if声明,你要指定检查它的值来代替。

尝试

if (Student[i] == 1)

0
投票

尝试sizeof(array)/sizeof(array[0])

在C ++中总是使用std::vector。有一些内置的功能和扩展功能。

std::vector具有返回在矢量元素的数量的方法size()

(是的,这是舌头在脸颊的答案)

© www.soinside.com 2019 - 2024. All rights reserved.