I want the user to put ten numbers in a row to fill my array with values.
Example:
1 2 3 4 5 6 7 8 9
constint s(10);
int v[s], i, value;
for(i = 0; i < s; i++)
{
cout << "Enter ten numbers in a row and seperate them with ','.;
cin >> v[i];
}
I want the user to put in '1, 2, 3,...n' to fill the array with values. As it is now the user have to put in a number and press enter, put in another value and press enter.
#include <iostream>
usingnamespace std;
int main()
{
constint s(10);
int v[s];
char numbers[109]; //the char array in which you will store the imput of the user
char buffer [s]; //char array that will act as a buffer to hold each number delimited by ','
int aux=0; //I used this var to keep track of position in int array v[]
int aux1=0; //I used this var to keep track of position in char array buffer[]
/*Init Vector*/
for(int i=0; i<s; i++)
v[i] = 0;
//<<<<<<<<<<<<<<<<<<<<<<<<<<
/*Get User input */
cout<<"Enter ten numbers in a row and seperate them with ','.";
cin.getline(numbers,255);
//<<<<<<<<<<<<<<<<<<<<<<<<<<
/*Process array*/
for(int i=0; i<109; i++)
{
if(numbers[i]!=',')
{
buffer[aux1] = numbers[i];
aux1++; //increas position of buffer
}
else
{
v[aux] = atoi(&buffer[0]); //transform buffer char array in int value and insert it in v[aux]
aux++; // increas position of v
aux1 =0; //reset position of buffer
memset(buffer, '\0', sizeof(buffer)); //clear buffer
}
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<
/*Display v[] content*/
for(int i=0; i<s; i++)
{
cout<<v[i]<<endl;
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<
/*w8 for user to press key to exit*/
cin.get();
cin.get();
return 0;
}
User is forced to end the input with ',' so that the last value will be accepted
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
vector<int> v;
string numbers; //the string array in which you will store the imput of the user
string buffer ; //string that will act as a buffer to hold each number delimited by ','
/*Get User input */
cout<<"Enter ten numbers in a row and seperate them with ','.";
getline(cin,numbers);
/*Process array*/
for(int i=0; i<=numbers.size(); i++)
{
if(numbers[i]!=',' &&
i <= (numbers.size()-1))
{
buffer += numbers[i];
}
else
{
v.push_back( atoi(&buffer[0]) ); //transform buffer string in int value and insert it in v
buffer.clear();
}
}
/*Display v[] content*/
for(int i=0; i<v.size(); i++)
{
cout<<v[i]<<endl;
}
/*w8 for user to press key to exit*/
cin.get();
cin.get();
return 0;
}