c++ - 如何用用户输入的字符填充数组,同时计算已使用了多少数组索引? (使用 cin.get)

标签 c++ arrays

我需要使用 get 函数并计算已填充的索引数量我遇到了几个问题。

好像这样使用cin.get只允许我填充数组,并不允许我统计数组中有多少个变量被填充了:

#include <iostream>

int main()
{
   char line[25];
   cout << " Type a line terminated by enter\n>";
   cin.get( line, 25 );

}

我觉得我需要使用 for 循环,如下所示,但问题是它不以 enter 结束,用户必须填充整个数组,我需要能够输入限制下的任意数量的字符。此外,该示例没有使用哨兵值,因此虽然它似乎可以解决这个问题,但它似乎并不是解决方案。

void fill_array(char array[], int max_count, int& num_used)
{
    char input;
    int index = 0;

    cout << "Enter a text string to test" << endl;
    for( index = 0;index < max_count; index++)
    {
         cin.get(input);
         array[index] = input;
         num_used++;
    }
}

最佳答案

您可以使用 gcount获取上次未格式化操作读取的字符数,如 cin.get

char line[25];
cout << " Type a line terminated by enter\n>";
cin.get( line, 25 );
std::streamsize read_chars = cin.gcount();

关于c++ - 如何用用户输入的字符填充数组,同时计算已使用了多少数组索引? (使用 cin.get),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13225083/

相关文章:

c++ - endl 不适用于 wstring (unicode)

c++ - 检测编译时是否存在 long long

c++ - meego支持的编程语言

c++ - 警告 C4552 : '<' : operator has no effect; expected operator with side-effect

ios - 从数组中获取前 10 个对象

c++ - 是否可以使用 operator new 和 initialiser 语法初始化非 POD 数组?

c++ - 奇怪的 C++ 语法

javascript - 根据不同对象数组中的属性和值过滤对象数组

php array_search 0 索引

JavaScript 循环正在更改数据源数组以及结果 - 为什么会这样?