Initialization and passing an array - c++

I am trying to create a program that will draw using a single dimensional array however I am having a hard time initializing the array using only one cin statement. A sample input that the user in supposed to look like
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;
}
}
How would I initialize the array with the sample input given and then pass it to a function to be used to draw

Here's a simple (perhaps unsafe but then again don't use std::cin for safety) implementation that seems to work for reading in the numbers:
#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;
}
And here's a sample run:
$ ./a.out
Input numbers: 1 2 3 4
1
2
3
4

I think you need a parse to decode the input. something like following:
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);
......
}

Here is a version of a program that lets you input a series of numbers with only one cin line with the help of stringstream, but the only difference is that it stores the input in a vector. It then draws a histogram chart based on the input.
Just press the <ENTER> key twice to let the program know that you are done with the inputting of the numbers.
#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;
}
}

Related

cant get the output to show in my outputfile.txt

#include <iostream>
#include <fstream>
void function(){
char ch;
int num;
int n;
int index = 0;
std::cout << "enter how manny letter you need to translate first: ";
std::cin >> n;
while (index < n){
std::cin >> ch >> num;
std::cout << char(ch+num)<<" ";
index++;
}
}
int main() {
std::ofstream outfile;
outfile.open("D:\\outfile.txt");
function();
outfile << function;
return 0;
}
this code asks for the number of letters you want to include ex:3
then you enter the letters with the a number, this number gets added to its ascii value
ex: a 1, out: b,
all of this is done in a void and i want the output "being the new letters" to be in the text file
the code always prints out 1 instead of the output letters inside the txt file

3-3. Write a program to count how many times each distinct word appears in its input

In this:
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin; using std::vector; using std::endl;
using std::string;
int main(){
cout << "enter strings: " << endl;
string s;
vector<string> in;
vector<string> out;
vector<int> count;
while(cin >> s)
in.push_back(s);
out.push_back(in[0]);
count.push_back(1);
int index = 0;
for(int i=0;i<in.size();i++){
if(out[index]==in[i])
(count[index])++;
else{
out.push_back(in[i]);
count.push_back(1);
index++;
}
}
cout << endl;
for(int i=0;i<count.size();i++)
cout << "i: " << i << "\tval: " << count[i] << endl;
}
I am not sure hot make the variable index to move only forward in count vector to count only those words that have already occure. Can someone help? exercise from book Accelerated C++ Practical Programming by Example
If you can't use std::map, you can associate the word with the frequency:
struct Info
{
std::string word;
int frequency;
};
//...
std::vector<Info> database;
//...
std::string word;
while (std::cin >> word)
{
// Find the word:
const size_t length = database.size();
for (unsigned int i = 0; i < length; ++i)
{
if (database[i].word == word)
{
database[i].frequency++;
break;
}
}
if (i >= length)
{
Info new_info{word, 0};
database.push_back(new_info);
}
}
The above code also shows that you should only insert words that are duplicates. No need to input all the words, then do the processing.

How can I use vector for entering numbers?

I want to enter names, student numbers and student scores and display this information.
I used arrays in this way:
#include "stdafx.h"
#include <iostream>
#include <string>
#define size 3
using namespace std;
class student{
public:
void vrod();
void dis();
int stno,score,i,n;
};
void student::vrod(){
cout<<"name=";
cin>>name;
cout<<"stno=";
cin>>stno;
cout<<"score=";
cin>>score;
}
void student::dis(){
cout<<"name="<<name<<"\n"<<"stno="<<stno<<"\n"<<"score="<<score<<"\n";
}
int main(){
int i, j=0,n,;
string h;
student st[size];
while (j<3){
st[j].vrod();
j++;}
j=0;
while (j<3){
st[j].dis();
j++;}
cin.get();
cin.get();
}
According to recommendation of my friends, I used vector in this way:
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<sstream>
#include<string>
#define n 3
using namespace std;
int main()
{
int input;
string names;
vector<int> stno,score;
vector<string> name;
cout<<"Enter the number of inputs: ";
cout << "Enter your numbers to be evaluated: " << endl;
for(int i=0;i<n;i++){
cout<<"student No.=";
cin >> input;
stno.push_back(input);
}
for(int i=0;i<n;i++){
cout<<"scor=";
cin >> input;
score.push_back(input);
}
for(int i=0;i<n;i++){
cout<<"name=";
cin >> names;
name.push_back(names);
}
for(int i=0;i<stno.size();i++)
cout<<stno[i];
for(int i=0;i<score.size();i++)
cout<<score[i];
for(int i=0;i<name.size();i++)
cout<<name[i];
cin.get();
cin.get();
}
Do you have any opinion to improve the second code written via vector? Can I save information from one student including student numbers and student scores in one position in vector like arrays? I mean for example if my n is 3, I enter the information of students in three positions like arrays(student st[size];)
Can I save information from one student including student numbers and
student scores in one position in vector like arrays? I mean for
example if my n is 3, I enter the information of students in three
positions like arrays(student st[size];)
Yes you can. A std::vector is a dynamic array that expands. So you could do something like this...
std::vector<student> my_vector;
for(int i = 0; i < n; i++)
{
student new_student;
cout << "Number: "
cin >> new_student.number;
cout << "Score: "
cin >> new_student.score;
cout << "Name: "
cin >> new_student.name;
my_vector.push_back(new_student);
}
//Accessing
std::cout << "Hello my name is: " + my_vector[0].name;
//Setting
vector[0].name = "Cranky Kong";
std::cout << "Hello my name is: " + my_vector[0].name;

Input values into a vector until the end of input?

So I want the user to input something like this:
0 15 72 34 92 8
and I want to fill a vector of integers with these numbers.
Here is what I have:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> V;
cout << "Please enter the numbers separated by \n";
cout << "spaces, then press the \"Enter\" key.\n\n";
int temp;
while (cin >> temp)
{
V.push_back(temp);
}
// The programs gets to this point and continuously asks for input
// Print the vector
cout << "The vector contains [ ";
for(int i = 0; i < V.size(); i++)
cout << V.at(i) << " ";
cout << "], ";
}
Modify your code based on this example. It takes input from user until user enters -1.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int number;
vector<int> userInput;
do
{
cout << "Enter a number (-1 to quit): ";
cin >> number;
userInput.push_back(number);
} while (number != -1);
for (vector < int >::iterator it = userInput.begin(); it < userInput.end() - 1; it++)
{
cout << endl << *it;
}
system("pause");
return 0;
}
First, read the entire line as a string using getline and after that fetch every integer and push it into the integer array.
vector<int> v;
string buffer;
int data;
getline(cin, buffer);
istringstream iss(buffer);
while (iss >> data)
v.push_back(data);

How to cin values into a vector

I'm trying to ask the user to enter numbers that will be pushed into a vector,
then using a function call to count these numbers.
why is this not working? I'm only able to count the first number.
template <typename T>
void write_vector(const vector<T>& V)
{
cout << "The numbers in the vector are: " << endl;
for(int i=0; i < V.size(); i++)
cout << V[i] << " ";
}
int main()
{
int input;
vector<int> V;
cout << "Enter your numbers to be evaluated: " << endl;
cin >> input;
V.push_back(input);
write_vector(V);
return 0;
}
As is, you're only reading in a single integer and pushing it into your vector. Since you probably want to store several integers, you need a loop. E.g., replace
cin >> input;
V.push_back(input);
with
while (cin >> input)
V.push_back(input);
What this does is continually pull in ints from cin for as long as there is input to grab; the loop continues until cin finds EOF or tries to input a non-integer value. The alternative is to use a sentinel value, though this prevents you from actually inputting that value. Ex:
while ((cin >> input) && input != 9999)
V.push_back(input);
will read until you try to input 9999 (or any of the other states that render cin invalid), at which point the loop will terminate.
You need a loop for that. So do this:
while (cin >> input) //enter any non-integer to end the loop!
{
V.push_back(input);
}
Or use this idiomatic version:
#include <iterator> //for std::istream_iterator
std::istream_iterator<int> begin(std::cin), end;
std::vector<int> v(begin, end);
write_vector(v);
You could also improve your write_vector as:
#include <algorithm> //for std::copy
template <typename T>
void write_vector(const vector<T>& v)
{
cout << "The numbers in the vector are: " << endl;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}
Other answers would have you disallow a particular number, or tell the user to enter something non-numeric in order to terminate input. Perhaps a better solution is to use std::getline() to read a line of input, then use std::istringstream to read all of the numbers from that line into the vector.
#include <iostream>
#include <sstream>
#include <vector>
int main(int argc, char** argv) {
std::string line;
int number;
std::vector<int> numbers;
std::cout << "Enter numbers separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number)
numbers.push_back(number);
write_vector(numbers);
}
Also, your write_vector() implementation can be replaced with a more idiomatic call to the std::copy() algorithm to copy the elements to an std::ostream_iterator to std::cout:
#include <algorithm>
#include <iterator>
template<class T>
void write_vector(const std::vector<T>& vector) {
std::cout << "Numbers you entered: ";
std::copy(vector.begin(), vector.end(),
std::ostream_iterator<T>(std::cout, " "));
std::cout << '\n';
}
You can also use std::copy() and a couple of handy iterators to get the values into the vector without an explicit loop:
std::copy(std::istream_iterator<int>(stream),
std::istream_iterator<int>(),
std::back_inserter(numbers));
But that’s probably overkill.
you have 2 options:
If you know the size of vector will be (in your case/example it's seems you know it):
vector<int> V(size)
for(int i =0;i<size;i++){
cin>>V[i];
}
if you don't and you can't get it in you'r program flow then:
int helper;
while(cin>>helper){
V.push_back(helper);
}
If you know the size of the vector you can do it like this:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (auto &it : v) {
cin >> it;
}
}
One-liner to read a fixed amount of numbers into a vector (C++11):
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
#include <cstddef>
int main()
{
const std::size_t LIMIT{5};
std::vector<int> collection;
std::generate_n(std::back_inserter(collection), LIMIT,
[]()
{
return *(std::istream_iterator<int>(std::cin));
}
);
return 0;
}
If you know the size use this
No temporary variable used just to store user input
int main()
{
cout << "Hello World!\n";
int n;//input size
cin >> n;
vector<int>a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
//to verify output user input printed below
for (auto x : a) {
cout << x << " ";
}
return 0;
}
You need a second integer.
int i,n;
vector<int> V;
cout << "Enter the amount of numbers you want to evaluate: ";
cin >> i;
cout << "Enter your numbers to be evaluated: " << endl;
while (V.size() < i && cin >> n){
V.push_back(n);
}
write_vector(V);
return 0;
You probably want to read in more numbers, not only one.
For this, you need a loop
int main()
{
int input = 0;
while(input != -1){
vector<int> V;
cout << "Enter your numbers to be evaluated: " << endl;
cin >> input;
V.push_back(input);
write_vector(V);
}
return 0;
}
Note, with this version, it is not possible to add the number -1 as it is the "end signal".
Type numbers as long as you like, it will be aborted when you type -1.
cin is delimited on space, so if you try to cin "1 2 3 4 5" into a single integer, your only going to be assigning 1 to the integer, a better option is to wrap your input and push_back in a loop, and have it test for a sentinel value, and on that sentinel value, call your write function. such as
int input;
cout << "Enter your numbers to be evaluated, and 10000 to quit: " << endl;
while(input != 10000) {
cin >> input;
V.push_back(input);
}
write_vector(V);
You can simply do this with the help of for loop
->Ask on runtime from a user (how many inputs he want to enter) and the treat same like arrays.
int main() {
int sizz,input;
std::vector<int> vc1;
cout<< "How many Numbers you want to enter : ";
cin >> sizz;
cout << "Input Data : " << endl;
for (int i = 0; i < sizz; i++) {//for taking input form the user
cin >> input;
vc1.push_back(input);
}
cout << "print data of vector : " << endl;
for (int i = 0; i < sizz; i++) {
cout << vc1[i] << endl;
}
}
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string>V;
int num;
cin>>num;
string input;
while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
//cin>>input;
V.push_back(input);
num--;
if(num==0)
{
vector<string>::iterator it;
for(it=V.begin();it!=V.end();it++)
cout<<*it<<endl;
};
}
return 0;
};
#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
vector<string> v;
string line,t;
getline(cin,line);
istringstream iss(line);
while(iss>>t)
v.push_back(t);
vector<string>::iterator it;
for(it=v.begin();it!=v.end();it++)
cout<<*it<<endl;
return 0;
}
In this case your while loop will look like
int i = 0;
int a = 0;
while (i < n){
cin >> a;
V.push_back(a);
++i;
}
The initial size() of V will be 0, while int n contains any random value because you don't initialize it.
V.size() < n is probably false.
Silly me missed the "Enter the amount of numbers you want to evaluate: "
If you enter a n that's smaller than V.size() at that time, the loop will terminate.
Just add another variable.
int temp;
while (cin >> temp && V.size() < n){
V.push_back(temp);
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x,n;
cin>>x;
vector<int> v;
cout<<"Enter numbers:\n";
for(int i=0;i<x;i++)
{
cin>>n;
v.push_back(n);
}
//displaying vector contents
for(int p : v)
cout<<p<<" ";
}
A simple way to take input in vector.
These were two methods I tried. Both are fine to use.
int main() {
int size,temp;
cin>>size;
vector<int> ar(size);
//method 1
for(auto i=0;i<size;i++)
{ cin>>temp;
ar.insert(ar.begin()+i,temp);
}
for (auto i:ar)
cout <<i<<" ";
//method 2
for(int i=0;i<size;i++)
{
cin>>ar[i];
}
for (auto i:ar)
cout <<i<<" ";
return 0;
}
would be easier if you specify the size of vector by taking an input :
int main()
{
int input,n;
vector<int> V;
cout<<"Enter the number of inputs: ";
cin>>n;
cout << "Enter your numbers to be evaluated: " << endl;
for(int i=0;i<n;i++){
cin >> input;
V.push_back(input);
}
write_vector(V);
return 0;
}
I ran into a similar problem and this is how I did it. Using &modifying your code appropriately:
int main()
{
int input;
vector<int> V;
cout << "Enter your numbers to be evaluated: "
<< '\n' << "type "done" & keyboard Enter to stop entry"
<< '\n';
while ( (cin >> input) && input != "done") {
V.push_back(input);
}
write_vector(V);
return 0;
}
cout << "do you like to enter the sem 2 score "<<endl;
cin >> sem2;
if (sem2 == 'Y' || sem2 == 'y')
{
cout << "enter your subject count ";
cin >> subjectcount;
cout << " enter your scores :";
for (int i = 0; i < subjectcount; i++)
{
double ip;
cout << (i+1) << " st score ";
cin >> ip;
sem2score.push_back(ip);
}
}
You can extract numbers by this way:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int aux;
char c='\n';
char a;
while(scanf("%d", &aux))
{
cout<<aux<<endl;
if(scanf("%c",&a) && a==c)
break;
}
return 0;
}