【问题标题】:How to count elements of array in c++如何在 C++ 中计算数组的元素
【发布时间】:2016-09-01 13:09:16
【问题描述】:

我有一个特定大小的数组(例如 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)]

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

【问题讨论】:

  • s/if (Student[i]=1)/if (Student[i]==1)/ - 也为了所有体面的事物,请启用编译器警告并注意它们(例如gcc -Wall ...)。
  • 如果您不知道用户将输入多少个元素,请使用std::vector。
  • 首先,启用更多的编译器警告。然后按照How to Ask 中的说明在所有调试问题中包含minimal reproducible example 和清晰的问题陈述。最后:每个问题一个问题。
  • But this code make an error, what is the error? 你告诉我们。不知道错误怎么知道有错误?
  • 发布一个完整的例子! Student[] 是如何定义的?它是如何初始化的?用户如何输入数据?如果没有这些信息,我们将无法真正帮助您。看来很多程序员都准备好帮忙写代码了,你就是不要让他们。

标签: c++ arrays loops if-statement for-loop


【解决方案1】:

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

在 C++ 中始终使用std::vector。有几个内置功能和扩展功能。

std::vector 有一个方法size(),它返回向量中元素的数量。

(是的,这是半开玩笑的回答)

【讨论】:

  • 你能不能写个代码举例说明一下?
  • OP 不想要数组的大小,他想知道输入了多少元素。此外,您的 sizeof 解决方案永远不应在 C++ 中使用。它不安全并且会给出错误的结果,模板解决方案更胜一筹。
  • @Revolver_Ocelot 它怎么不安全? sizeof(array)/sizeof(array[0]) 将始终为您提供数组的大小。
  • @Revolver_Ocelot 那么它不是一个数组而是一个指针。不过,在数组上使用它总是安全的。
  • @Revolver_Ocelot 这是语言教学方式的问题。指针和数组是两个不同的东西,新生应该非常清楚。详细说明数组衰减为指针的情况,以便新程序员了解按值传递数组的陷阱。
【解决方案2】:

在if 语句中,您正在分配一个值而不是检查它。

试试

if (Student[i] == 1)

【讨论】:

  • 我试过 if (Student[i] == 1) ... 但还是有错误!
  • 你的学生变量是一个字符串数组。您不能将字符串与整数进行比较。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多