Programming FAQ

Reading input in C/C++

I was wondering how to tackle inputs in C++ when they ask for 2 numbers then u output after processing the 2 numbers. The thing is, they question said that the input will terminate at EOF. How do i do this in C?

Answer

With regards to detecting EOF, when scanf reaches the end of a file it returns an integer whose value is equivalent to the symbolic constant EOF.

So for reading input till the end, you can use the following code C code fragment:

while (scanf("%d %d", &num1, &num2) != EOF) {
 //code your solution here
}

Alternatively since scanf returns the number of items read you can also use

while (scanf("%d %d", &num1, &num2) == 2) {
 //do something with num1 and num2 to produce the output
}

Note that you should either use the scanf/printf pair of functions for doing I/O or the cin/cout objects but you should not mix them together i.e. use scanf for input and cout for output. This is because they make use of different internal buffers and this may lead problems.

If you want to use cin, then you can do something like this

while (cin >> num1 >> num2) {
 //process num1 and num2 to produce the output
}

If you are reading from file, you can use the following C code fragment

while( !feof(file_in) ) {
 //do scanf and processing
}

Another way is to do this:

while( fscanf(file_in, "%d %d", &a, &b) == 2) {
 //do something
}

The second method explicitly indicates that it is expecting 2 items. However, file errors or format errors will result in less than 2 entries being read, even if not at EOF.

 
programming_faq.txt · Last modified: 2007/12/29 09:37 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki