Converting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <iostream>
using namespace std;

int main ( void )
{
  const int size = 20;
  int array[size];
  int n, i, j;

  /* Fill the array */
 cout<<"Enter 20 random numbers";
  fflush ( stdout );
  for ( n = 0; n < size; n++ ) {
    if ( scanf ( "%d", &array[n] ) != 1 )
      break;
  }


This is in my text book and i am not familiar with stdio.h. Can anyone translate
scanf ( "%d", &array[n] ) != 1 in English and in iostream language?
cin >> array[n]

( will evaluate true if successful )
Sure. That's C function that accepts a format string and a variable list of arguments. The format %d is an integer and &array[n] is a pointer to array[n]. In this case, scanf reads an int from stdin and puts it in array[n]. It returns the number of successful reads, in this case 1 means that it worked.

The C++ alternative is:
1
2
3
// replaces line 15
cin >> array[n];
if( !cin.good() )


References:
http://cplusplus.com/reference/clibrary/cstdio/scanf/
http://cplusplus.com/reference/iostream/cin/
http://cplusplus.com/reference/iostream/istream/operator%3E%3E/

On successful reading of a data item, scanf function returns 1 (scanf essentially no. of data items read successfully. http://www.cplusplus.com/reference/clibrary/cstdio/scanf/).
The type of the data item to be read is mentioned by the conversion specifier. In our case %d meaning an integer is to be read. So wat the statement means is if we read an read an integer successfully that is scanf returns 1, continue reading more integers (till 20) else i.e. if scanf fails to read an integer at any time ( return value of scanf != 1) break the loop (stop reading for more integers).

cin >> array[n] ; is the iostream translation .
cin.good <-- what is good for?
and actually i apologize is not just scanf i don't understand
"fflush ( stdout); either. and what is the c++ alternative?
and one more what is
" printf ( "%d\n", array[i] );" in English and it's alternative?
Last edited on
cin.good() checks whether cin is in a good state which means that you can continue getting input http://www.cplusplus.com/reference/iostream/ios/good/
fflush ( stdout); is equivalent to cout.flush()
Topic archived. No new replies allowed.