我需要使用 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/