I created a program that let's the user input up to 10 integers and then it will print out the sum of the inputted integers. However I want to stop the program when the user tries to input more than 10 integers or when the user types in "DONE". I didn't really get it to work because when the user types in something other than an integer (including the string "DONE"), it will stop. I only want it to stop when the user types in "DONE". If the user types in something like "Hello" I want the program to crash.
This is how it should look:
Enter up to 10 numbers:
12
12
4
DONE
The sum of the integers is: 28
What's wrong with my code? I am referring to my void read_numbers function. As I mentioned, I want it to stop ONLY when the user inputs the string "DONE" or when the user inputs more than 10 integers.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Number_Type {
vector<int> numbers;
};
void read_numbers(Number_Type& number) {
int digit{};
string line;
// char space = ' ';
while ((line != "DONE") && (number.numbers.size() != 10)) {
cin >> digit;
getline(cin, line);
number.numbers.push_back(digit);
}
}
int number_sum(Number_Type const& number) {
int sum{};
for (int i{}; i < number.numbers.size(); ++i) {
sum += number.numbers[i];
}
return sum;
}
int main() {
Number_Type number;
cout << "Enter up to 10 numbers: " << endl;
read_numbers(number);
cout << "The sum of the integers is: " << number_sum(number);
}
Fist you have to read all your inputs as strings. Then you can use std::from_chars to check if your input was a valid integer (without having to do exception handling, which std::stoi will need). Example here (live demo https://onlinegdb.com/UANchB1mn)
#include <iostream>
#include <string>
#include <vector>
#include <charconv>
auto read_numbers(const std::size_t max_numbers)
{
std::vector<int> values;
int value{};
std::string input;
do
{
std::cout << "Enter number " << values.size() + 1 << " of " << max_numbers << " (or DONE to stop) : ";
std::cin >> input;
// std::stoi is an option but then you would need do exception handling
auto result = std::from_chars(input.data(), input.data() + input.size(), value);
if (result.ec == std::errc())
{
values.push_back(value);
}
}
while ((input != "DONE") && (values.size() < max_numbers));
return values;
}
int main()
{
auto values = read_numbers(3);
std::cout << "you entered : ";
for (const auto value : values)
{
std::cout << value << " ";
}
return 0;
}
The user will enter a list of numbers. The user should enter as many numbers as the user wishes. All the numbers should be stored in a variable, I am not trying to add them all up.
#include <iostream>
using namespace std;
int main()
{
// declare variables
double number,listOfNumbers;
bool condition;
cout << "Enter a starting number: ";
cin >> number;
condition = true;
while (condition)
{
if(number > 0)
{
cout << "Enter another number (type 0 to quit): ";
listOfNumbers = number;
cin>>listOfNumbers;
}
else
{
condition=false;
}
}
cout << listOfNumbers;
return 0;
}
Use a std:vector to hold the numbers, eg:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// declare variables
double number;
vector<double> listOfNumbers;
cout << "Enter numbers (type 0 to quit): ";
while ((cin >> number) && (number != 0))
{
listOfNumbers.push_back(number);
}
for(number : listOfNumbers)
cout << number << ' ';
return 0;
}
Some small modifications and the use of a std::listor std::vector to store the values, the vector will grow dynamicly as you run the program and relocate if it runs out of space, the list will allocate space for every new item both works here.
I also never use using namespace std although it is very common in tutorials to do.
The syntax auto const &i in last for loops requires some of the later C++ standards it will give you a unmutable reference to the item.
#include <iostream>
#include <list>
int main() {
// declare variables
double number;
std::list<double> listOfNumbers;
bool condition;
std::cout << "Enter a starting number: ";
std::cin >> number;
condition = true;
while (condition) {
if (number > 0) {
listOfNumbers.push_back(number);
std::cout << "Enter another number (type 0 to quit): ";
std::cin >> number;
} else {
condition = false;
}
}
for (auto const &i : listOfNumbers) {
std::cout << i << std::endl;
}
return 0;
}
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;
}
}
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;
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;
}