如何确定数组中的元素数量

时间:2018-03-27 20:28:31

标签: c++ arrays

我的问题是:

使用 cin.getline() 输入char数组时,有没有办法计算char数组的字母?

我尝试使用 sizeof() ,但它只是给我输入的数字作为数组的大小。

3 个答案:

答案 0 :(得分:1)

如果您使用cin.getline(),则表示您正在将字符读入缓冲区。

char buffer[100];
std::cin.getline(buffer, 100);

读取的实际字符数可从流中检索。

std::size_t count = cin.gcount();

注意该行可能会更长,因为当缓冲区已满时此API将停止读取(如果这发生在行尾之前)。因此,如果您使用此界面,则可能需要测试流上的failbit以确保已读取整行。

char buffer[100];
std::cin.getline(buffer, 100);
if (std::cin.rdstate() & std::ios::failbit) {
    std::cin.clear();
    // Here just ignoreing the rest of the line.
    // But you could read the rest of the data or something else.
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

或者,您可以使用std::getline()并检索字符串。

std::string line = std::getline(std::cin);
std::cout << line.size();   // The size is now part of the string.

此界面更直观。

答案 1 :(得分:0)

最好使用(std :: string),但如果确定使用char数组,则可以在(c-string)库中使用strlen()。

答案 2 :(得分:-1)

在声明变量num_of_elements=0;后,您可以在arraylength上创建for循环。  并在该循环中将每个计数器编号添加到声明的变量。

当循环结束时打印该变量。

相关问题