Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I know its a silly question but i have to ask

Basically i wanna input array elements from user until return key is pressed.

I tried but not able to complete my task... :(

C#
printf("\nEnter array elements and press enter to finish input\n");
do
{
    scanf("%d",&a[i]);
    i++;
    printf("\t");
}
while('\n');
Posted
Comments
Sergey Alexandrovich Kryukov 27-Oct-13 21:40pm    
One problem is that you don't know how many array elements you may need in advance, so you need some data structure which can add elements one by one, for example, linked list (a useful exercises itself).
—SA

1 solution

Please note that scanf reads the standard input until and including the return key! The return key is a mandatory part of every single input!

However, you can check the return code from scanf: if successful, it returns the number of variables read. This number should be 1 for each correctly entered number, or 0 if no number was entered. So you could change your code to

C++
int value;
while (scanf("%d", &value)) {
  ++i;
  // store value into array
}

Like SA said, you need to make sure that your array is actually big enough, or you need to use a dynamic container such as a list. That's why I introduced a temporary variable for reading the value.
 
Share this answer
 
Comments
nv3 28-Oct-13 9:07am    
5.
Atul Khanduri 31-Oct-13 8:29am    
So it means there is no way input variables until "RETURN" key is pressed....:/
And okay, if u say there is no way because of scanf, but can we I/P values till "TAB" key or any other specific key is pressed(without knowing its ASCII value)...
Stefan_Lang 31-Oct-13 9:18am    
The reading continues until you press [return]. The same is true for every other function that reads from console. You can of course use a different input character to detect if the user wishes to end the input loop. But it's eqully valid to just check the result of scanf() as described above.
Atul Khanduri 31-Oct-13 9:59am    
Your above code checks for a non-integer value and if it occurs then it breaks the loop. But i want to break the loop when any white-space character (Space , Tab) and of course Return is entered.
Stefan_Lang 31-Oct-13 10:35am    
Then you must read the actual input as string rather than interpret it as an integer. The "%d" in your format string forces scanf to discard anything that doesn't belong to the number it expects to read, including all whitespace characters. You could use gets() instead to read the input as string, then check that string, and then convert it to int using atoi().

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900