Hello guys I'm having trouble trying to implement the enter key part of my program
int list[50];
int i = 0;
while (/*enter key has not been pressed*/&& i < 50){
cin>>list[i];
i++;
}
How its supposed to work is, it will take in integers separated by spaces and store them into the array. It should stop accepting input when the enter key has been pressed.
PS I'm posting this from my phone that's why I can't format the text properly. If there's any problem with syntax, it could probably just be ignored setting as I'm only concerned with the"enter key" part.
you can use a string stream, basically you read the whole line into a string and then you start reading integers from that string into your array.
reading a string will terminate when you hit enter, so I think that would work out for you
#include <iostream>
#include <string>
#include <sstream>
using namespace :: std; // bad idea, I am just lazy to type "std" so much
int main (){
const int arrSize = 5;
int arr [arrSize] = {0}; //initialize arr zeros
string line;
getline(cin,line);
cout <<"you entered " << line<<endl; // just to check the string you entered
stringstream ss (line);
int i = 0;
while ( ss>>arr[i++] && i < arrSize); // this might look a bit ugly
for (int i =0; i < arrSize; i++) // checking the content of the list
cout<<arr[i]<<" ";
getchar();
return 0;
}
note that doesn't test for false input from the user ( like a letter instead of a number).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With