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;
}
Related
I'm relatively new to C++ and I'm trying to write some code that asks a user to enter numbers and use -999 as a sentinel value to end the input loop. The numbers they enter must populate an array to be used in a binary tree later. The issue I'm having is the loop doesn't terminate if -999 is entered, and I also don't know how to read those values into the array without specifying how large the array is. The program must dynamically size the array based on how many inputs were given. I have attached my code. Any help is greatly appreciated!
#include <iostream>
#include <string.h>
//#include "binarySearchTree.h"
//#include "binaryTree.h"
using namespace std;
int i;
int n;
struct Node {
int data;
struct Node* left;
struct Node* right;
}
Node(int val)
{
data = val;
left = NULL;
right = NULL;
};
int main() {
//struct Node* root = new Node(1);
cout << "Enter values up to -999: \n";
int numbers[] = {};
for(int i =0; i!=999; i++){
cin >> numbers[i];
}
cout << "\nYour numbers are: ";
for(int j=0; j<=sizeof(numbers) ; j++){
cout << numbers[j] << " ";
}
return 0;
}
Here is a program that does what you want.
#include <iostream>
#include <vector>
// never, ever use using namespace std;
int main()
{
std::vector<int> input; // this is the way to spell "an array that can grow as needed"
// int numbers[] = {}; is not one.
int number;
while (std::cin >> number // check whether the input is successful, i.e. a number
// is entered. entering a non-number or an
// end-of-file indicator is a failure
&& number != -999) // and whether that number is not -999
{
input.push_back(number); // add it to the end of our growing-as-needed array
}
for (auto i : input) // that's how you enumerate entries in the array
{
std::cout << i << " ";
}
std::cout << "\n"; // print a newline when you are done
}
Live demo
Beside all other problems, the main problem is here:
for(int i =0; i!=999; i++){
cin >> numbers[i];
}
You are reading from the standard input into the i-th element of the array numbers. You are comparing i with 999, which basically makes no sense. Why comparing i? And why comparing it with 999, instead of -999?
Let's try to fix it. Start with an empty infinite loop:
while (true) {
// Read
// Check
// Use
}
Read an integer:
while (true) {
// Read
int val;
cin >> val;
// Check
// Use
}
Now let's check if we managed to read something and if not let's exit from the loop.
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
// Use
}
We need to exit from the loop also if we read a -999:
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
}
Now you want to put it in the i-th position of numbers, so:
int i = 0;
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
numbers[i] = val;
++i;
}
Ok, now we have a working loop (hopefully). What other problems you have in your code?
int numbers[] = {};
j<=sizeof(numbers)
You cannot define arrays without a compile time size in C++. Use std::vector<>.
Then, the sizeof operator doesn't do what you think it does. Save it for (much?) later. Use std::vector::size(). But for starters, you can assume that 1000 numbers will be enough for everyone (Bill Gates docet), and keep the count in variable i:
#include <iostream>
using namespace std;
int main()
{
cout << "Enter values. Use -999 to stop entering values.\n";
int numbers[1000]; // We accept 1000 numbers at most 🤮
int i = 0;
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
numbers[i] = val;
++i;
}
cout << "Your numbers are: ";
for (int j = 0; j < i; j++) {
cout << numbers[j] << " ";
}
cout << '\n';
return 0;
}
Switching to std::vector<> is much better. And learn Why is "using namespace std;" considered bad practice?:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Enter values. Use -999 to stop entering values.\n";
std::vector<int> numbers;
while (true) {
// Read
int val;
std::cin >> val;
// Check
if (std::cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
numbers.push_back(val);
}
std::cout << "Your numbers are: ";
for (int j = 0; j < numbers.size(); j++) {
std::cout << numbers[j] << " ";
}
std::cout << '\n';
return 0;
}
Finally, if you think that while(true) {} is ugly, you can use other versions of the same loop, e.g.:
for (int val; std::cin >> val && val != -999;) {
numbers.push_back(val);
}
When running the code to solve for the counting operations the answer will always come out to 3 operations. Why does count always output 3 even when it does not fit the criteria?
#include <string>
#include <iostream>
using namespace std;
int main() {
string input1;
string input2;
cout << "Enter first number: ";
cin >> input1;
cout << endl;
cout << endl;
cout << "Enter second number: ";
cin >> input2;
int count = 0;
for (int i = 0; i < 3; i++) {
int thing = (input1.at(i) + input2.at(i));
if (thing > 9) {
count++;
}
}
cout << count;
return 0;
}
There is internal typecasting being done here. From char to int as the result is required is in integer format and addition is being done. Therefore actually ASCII values are being added. For '0' it is 48. Therefore everytime the sum is greater than 9. And hence output is 3. The answer here will provide a better insight.
For your question this is a better way to do it. (subtract '0' from each digit char), therefore actually internally it becomes ASCII(digit) - ASCII(0), which will give you the actual digit
#include <string>
#include <iostream>
using namespace std;
int main() {
string input1;
string input2;
cout << "Enter first number: ";
cin >> input1;
cout << endl;
cout << endl;
cout << "Enter second number: ";
cin >> input2;
int count = 0;
for (int i = 0; i < 3; i++) {
int thing = (input1.at(i)-'0') + (input2.at(i)-'0');
if (thing > 9) {
count++;
}
}
cout << count;
return 0;
}
If you are doing mathematical operation you must use appropriate types for the variables. Since you have used strings as variable type , it will not give correct result as desired. For the given code to work try this.
int input1;
int input2;
For more examples on user inputs in c++
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;
}
}
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);