I am writing a code where I am asking user to assign value to an array and where user press enter key I want to assign a default value to array elements. Any idea how to proceed with this ?
I have tried using cin.get() method but it is not working. Here is my code :
#include<iostream>
#include<math.h>
#include<cmath>
using namespace std;
int main()
{
int n;
cout << "Enter array size: ";
cin >> n;
double y[n];
string input;
for(int i=0; i<n; i)
{
cout << "Enter Initial Velocity ( Default Value 0 ) : " ;
y[i] = cin.get();
if (input=="")
{
y[i]=0.0;
}
else
{
y[i]=stod(input);
}
}
}
CodePudding user response:
try this
#include <iostream>
using namespace std;
int main()
{
cout << "Press the ENTER key";
if (cin.get() == '\n')
cout << "Good job.\n";
else
cout << "I meant ONLY the ENTER key... Oh well.\n";
return 0;
}
CodePudding user response:
I've tried to change minimal things to make your code work as you've expected. Bunch of stuff can be improved, array creation, not including useless files, reducing the scope of local variables, also don't use using namespace std
- see this.
#include <math.h> //useless
#include <cmath> //useless
#include <iostream>
//#include <string> some compilers may require adding this
using namespace std; //bad practice
int main() {
int n;
cout << "Enter array size: ";
cin >> n;
double y[n]; //not a great way to create an array, fix this
cin.ignore();
//can be moved inside the loop
string input;
for (int i = 0; i < n; i) {
cout << "Enter Initial Velocity ( Default Value 0 ) : ";
getline(cin, input);
if (input == "") {
y[i] = 0.0;
} else {
y[i] = stod(input);
}
}
for (int i = 0; i < n; i ) {
if (i > 0) cout << ' ';
cout << y[i];
}
cout << '\n';
}