-
Input buffer question
Hi,
I'm new to the boards and C++. I was wondering how I could read in multiple values from a line of data. I have a part of the program I was working on, here:
Code:
cout << "Please enter" << x << " samples." << endl;
cin >> sample;
for (i = 1; i <= x; i++)
{
cout << "Sample " << i << " is " << sample << endl;
}
basically, what i am having problems with is reading in the "x" samples from the input buffer. I can do it with characters, but not numbers. Can anyone help?
-
Code:
cout << "Please enter" << x << " samples." << endl;
for (int i = 0; i < x; i++)
cin >> sample[x];
Something like that?
-
It depends on how the data is entered by the user. The >> operator is programmed to skip over any leading whitespace(spaces, tabs, newlines) and read in data until it encounters a whitespace character at which point it stops. So, if the user enters 3 numbers like this:
123
>> will read in 123--not 1. However, if the user enters data like this:
1 2 3
then >> will read in 1, and then the next time >> is used, it will read in 2, etc. In the latter case, if you want to read all the numbers at once, you can do this:
cin>>sample1>>sample2>>sample3;
-
yeah... guess so...but i want to do it for an unknown number of entries that the user would have entered in as 'x'
-
Code:
#include <vector>
using namespace std;
.
.
vector<int> sample;
cout << "Please enter" << x << " samples." << endl;
int tmp;
for (int i=0; i<x; ++i)
{
cin >> tmp;
sample.push_back(tmp);
}
for (int i=0; i<sample.size(); ++i)
{
cout << "Sample " << i << " is " << sample[i] << endl;
}
Or what SlyMaelstrom posted which uses an array.
-
Vector of course being more modern and potentially more useful depending on where you wanted to go from there.