C++ 如何确定数组中的元素数

C++ 如何确定数组中的元素数,c++,arrays,C++,Arrays,我的问题是: 当使用cin.getline()输入字符数组时,是否有方法对其字母进行计数 我尝试使用sizeof(),但它只给出我作为数组大小输入的数字。在声明变量num\u of\u elements=0后,可以在arraylength上创建for循环。 在该循环中,将每个计数器编号添加到声明的变量中 循环结束时,打印该变量。如果使用cin.getline()则将字符读入缓冲区 char buffer[100]; std::cin.getline(buffer, 100); 读取的实际字符数

我的问题是:

当使用
cin.getline()
输入字符数组时,是否有方法对其字母进行计数


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

在声明变量
num\u of\u elements=0后,可以在arraylength上创建for循环。
在该循环中,将每个计数器编号添加到声明的变量中


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

如果使用
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::string),但如果您决定使用char数组,则可以在(c-string)库中使用strlen()。

如果您使用的是c-style字符串,请使用
strlen()
。但是你为什么不使用
std::string
?根据我的理解,你可以使用
std::cin.gcount()
@Galik:这应该作为答案发布
std::string line = std::getline(std::cin);
std::cout << line.size();   // The size is now part of the string.