gpt4 book ai didi

c++ - 初始化并传递数组

转载 作者:行者123 更新时间:2023-11-28 05:32:07 25 4
gpt4 key购买 nike

我正在尝试创建一个将使用一维数组绘制的程序,但是我很难仅使用一个 cin 语句来初始化数组。用户应该看起来像的示例输入

1<space>2<space>34<space>3<space>2<space>1<space>0<space>10


#include<iostream>
using namespace std;
/*---------------------------------------------------------------------------------------
Prototypes
These are the prototype function(s) that will be used to to draw the row and columns
---------------------------------------------------------------------------------------*/
void draw(int nums);
//---------------------------------------------------------------------------------------
int main(){
const int MAX = 100;
int chart[MAX];
int nums;

cout << "Enter numbers for the chart" << endl;
cin >> nums;
draw(nums);

return 0;
}

void draw(int nums) {
cout << endl;
int row;

for (row = 0; row < nums; ++row) {
cout << "*" << endl;
}
}

我如何使用给定的示例输入初始化数组,然后将其传递给用于绘制的函数

最佳答案

这是一个简单的(可能不安全,但为了安全起见不要使用 std::cin)实现,它似乎适用于读取数字:

#include <iostream>
#include <list>
#include <sstream>
int main()
{
std::cout << "Input numbers: ";
// get input line
std::string input;
std::getline(std::cin, input);
std::stringstream ss(input);
// read numbers
std::list<int> numbers;
while(ss) {
int number;
ss >> number;
ss.ignore();
numbers.push_back(number);
}
// display input
for(const auto number: numbers) {
std::cout << number << std::endl;
}
return 0;
}

这是一个示例运行:

$ ./a.out
Input numbers: 1 2 3 4
1
2
3
4

关于c++ - 初始化并传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39240243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com