2016-08-31 9 views
0

Я пытаюсь создать программу, которая будет рисовать с использованием одномерного массива, однако мне сложно инициализировать массив, используя только один оператор 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; 
    } 
} 

Как бы инициализировать массив с входом образца заданного, а затем передать его в функцию, которая будет использоваться для рисования

ответ

1

Вот простой (возможно, небезопасным, но затем снова не использовать станд :: 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 
0

Я думаю, вам нужен синтаксический анализ для декодирования ввода. что-то вроде следующего:

void parse(const std::string& input, int output[], int MaxNum) 
{ 
    // parse the integer from the string to output. 
} 

int main(){ 
    ...... 
    std::string input; 
    cout << "Enter numbers for the chart" << endl; 
    cin >> input; 
    parse(input, chart, MAX); 
    ...... 
} 
0

enter image description here

Вот версия программы, которая позволяет вводить ряд цифр только один cin линии с помощью stringstream, но той лишь разницей, что он хранит вход в vector. Затем он рисует гистограмму на основе ввода.

Просто нажмите клавишу <ENTER>, чтобы программа знала, что вы закончили с ввода цифр.

#include <iostream> 
#include <iterator> 
#include <vector> 
#include <algorithm> 
#include <sstream> 
using namespace std; 

vector<int> Vector; 
string line; 

void drawchart(int max); 


int main() { 

    cout<<"Chart drawing program (Histogram) \n"; 
    cout<<"Enter a series of numbers. \n"; 
    cout<<"Seperate with a space, press <ENTER> TWICE to end input \n"; 
    cout<<" (e.g 2 3 4 5 6) > "; 

    if(!getline(cin, line)) return 1; 
    istringstream iss(line); 

    copy(istream_iterator<int>(iss), istream_iterator<int>(), back_inserter(Vector)); 

    copy(Vector.begin(), Vector.end(), ostream_iterator<int>(cout, ", ")); 

    cout<<"\nDrawing chart.. \n\n"; 

    drawchart(Vector.size()); 


    cout<<"Press ANY key to close.\n\n";  
    cin.ignore();cin.get(); 

return 0; 
} 

// draws a chart or hjistogram 
void drawchart(int max){ 
    for(int i = 0; i < max ; i++){ 
     for(int j = 0; j < Vector[i]; j++) cout << "*"; 
     cout << endl; 
    } 
} 
Смежные вопросы