Simple C Program - c++

Ok so I am trying to learn C and I want my user to input a value so I am using scanf. I started off not having the flushes, because nothing was comming up until I typed in two values. Now that I have them though I get the same problem there still is no output until after I type in two numbers. Here is my code:
#include <stdio.h>
using namespace std;
int main()
{
int i1, i2, sums;
printf( "Enter first integer\n" );
fflush(stdout);
scanf( "%d", &i1 );
printf( "Enter second integer\n" );
fflush(stdout);
scanf( "%d", &i2 );
sums = i1 + i2;
printf( "Sum is %d\n", sums );
fflush(stdout);
return 0;
}
Any help would be greatly appreciated.

The following works fine for me:
#include <stdio.h>
int main() {
int i1, i2, sums;
printf( "Enter first integer\n" );
scanf( "%d", &i1 );
printf( "Enter second integer\n" );
scanf( "%d", &i2 );
sums = i1 + i2;
printf( "Sum is %d\n", sums );
return 0;
}
and gives:
Enter first integer
1
Enter second integer
6
Sum is 7
This is using Cygwin under XP. What platform and compiler are you using?
Update: One possibility is that, because you're running from within the Eclipse environment, it may be doing some weird stuff that interferes with the normal I/O rules.
I'm pretty certain that stdout, even if it's not line buffered like stderr, will autoflush if you attempt to read from stdin (at least in most environments I've used, which is a few).
Eclipse may be fiddling around with the way it attaches the console to the program's actual I/O. I would try to compile the code to a standalone executable and then run it outside the Eclipse environment. If it runs fine there, then it's probably the interaction between Eclipse and the program.
As I stated, your program works fine under XP with Cygwin, even without the flushes.
Further explanation is warranted. As Jerry Coffin rightly points out in a comment, the C standard (c1x, 2009/03/01 draft) states:
5.1.2.1 para 6: The input and output dynamics of interactive devices shall take place as specified in 7.19.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input.
5.1.2.1 para 7: What constitutes an interactive device is implementation-defined.
7.9.13 para 3: When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.
7.9.13 para 7: At program startup, three text streams are predefined and need not be opened explicitly - standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.
What may be happening is that the way Eclipse interacts with the programs input and output may be causing the program to not recognize stdout as an interactive device. It would then be fully buffered, meaning that you wouldn't see the output until the buffer is full, or the program terminates.

I think you need "\n" in side the "scanf". Like this.
scanf( "%d\n", &i2 );
Try it.

i think your are flushing out the wrong stuff , try flushing scanf using stdin not using stdout,just like this
#include
main()
{
int i, j,sums;
printf("enter the first integer\n");
scanf("%d",&i);
fflush(stdin);
printf("enter the second integer\n");
scanf("%d",&j);
fflush(stdin);
sums = i + j;
printf("sum is %d\n",sums);
//fflush(stdin);
getchar();
}

Related

Reading large strings in c++ [duplicate]

I am trying to read in a string of length in 10^5 order. I get incorrect string if the size of string grows beyond 4096.
I am using the following code
string a;
cin>>a;
This didn't work then I tried reading character by character by following code
unsigned char c;
vector<unsigned char> a;
while(count>0){
c = getchar();
a.push_back(c);
count--;
}
I have done necessary escaping for using getchar this also had the 4096 bytes problem. Can someone suggest a workaround or point to correct way of reading it.
It is because your terminal inputs are buffered in the I/O queue of the kernel.
Input and output queues of a terminal device implement a form of buffering within the kernel independent of the buffering implemented by I/O streams.
The terminal input queue is also sometimes referred to as its typeahead buffer. It holds the characters that have been received from the terminal but not yet read by any process.
The size of the input queue is described by the MAX_INPUT and _POSIX_MAX_INPUT parameters;
By default, your terminal is in Canonical mode.
In canonical mode, all input stays in the queue until a newline character is received, so the terminal input queue can fill up when you type a very long line.
We can change the input mode of terminal from canonical mode to non-canonical mode.
You can do it from terminal:
$ stty -icanon (change the input mode to non-canonical)
$ ./a.out (run your program)
$ stty icanon (change it back to canonical)
Or you can also do it programatically,
To change the input mode programatically we have to use low level terminal interface.
So you can do something like:
#include <iostream>
#include <string>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int clear_icanon(void)
{
struct termios settings;
int result;
result = tcgetattr (STDIN_FILENO, &settings);
if (result < 0)
{
perror ("error in tcgetattr");
return 0;
}
settings.c_lflag &= ~ICANON;
result = tcsetattr (STDIN_FILENO, TCSANOW, &settings);
if (result < 0)
{
perror ("error in tcsetattr");
return 0;
}
return 1;
}
int main()
{
clear_icanon(); // Changes terminal from canonical mode to non canonical mode.
std::string a;
std::cin >> a;
std::cout << a.length() << std::endl;
}
Using this test-program based on what you posted:
#include <iostream>
#include <string>
int main()
{
std::string a;
std::cin >> a;
std::cout << a.length() << std::endl;
}
I can do:
./a.out < fact100000.txt
and get the output:
456574
However, if I copy'n'paste from an editor to the console, it stops at 4095. I expect that's a limit somewhere in the consoles copy'n'paste handling. The easy solution to that is of course to not use copy'n'paste, but redirect from a file. On some other systems, the restruction to 4KB of input may of course reside somewhere else. (Note that, at least on my system, I can happily copy and paste the 450KB of factorial result to another editor window, so in my system it's simply the console buffer that is the problem).
This is much more likely to be a platform/OS problem than a C++ problem. What OS are you using, and what method are you using to get the string fed to stdin? It's pretty common for command-line arguments to be capped at a certain size.
In particular, given that you've tried reading one character at a time, and it still didn't work, this seems like a problem with getting the string to the program, rather than a C++ issue.

Why reading from a stream does not require a buffer flush

Just started C++ learning by C++ Primer 5th ed.
The very first example of the book on page 6 is as followed
#include <iostream>
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
return 0;
}
The manipulator endl insert newline and flush the buffer.
soon followed by the code snipe in the page 7, the author emphasized that
Programmers often add print statements during debugging. Such
statements should always flush the stream. Otherwise, if the program
crashes, output may be left in the buffer, leading to incorrect
inference about where the program crashed
From the code example and the emphasized warning I feel it is important to do the flush when writing to a Stream
Here is the part I don't understand, how a bout reading from a stream case, such as std::cin, is there any necessary to do the flush then?
Appended Question:
#include <iostream>
int main()
{
int sum = 0, val = 1;
while (val <= 5) {
sum += val;
++val;
std::cout << sum << std::endl; //test
}
}
When I changed the line marked with test to std::cout << sum << '\n';, there is no visual difference in the console. Why is that, isn't it supposed to print as follows if there is no flush for each loop?
1
1 3
1 3 6
1 3 6 10
1 3 6 10 15
Thanks
Even if #Klitos Kyriacou is right when he says you should create a new post for a new question, it seems to me that both your questions arise from the same misunderstanding.
Programmers often add print statements during debugging. Such statements should always flush the stream. Otherwise, if the program crashes, output may be left in the buffer, leading to incorrect inference about where the program crashed
This quote does not mean that you need to flush every buffer in your program to create any output on the console.
By flushing the buffers you can make sure that the output is printed before the next line of code is executed.
If you don't flush the buffers and your program finishes, the buffers will be flushed anyway.
So, the reason you see the same output on the console with std::endl and \n is, that exactly the same text is printed to the console. In the former case, the output might be there slightly earlier, as the buffers are flushed early. In the latter case, the buffers are flushed later, but they will be flushed at some time.
What the quote talks about is the case when your program does not exit gracefully, e.g. when your program crashes or is interrupted by the OS. In these cases, your output might not be written to the console when you did not explicitly flush the buffers.
What the quote wants you to know is: Whenever you want to debug a program that crashes, you should explicitly flush the buffers to make sure your debug output is printed to the console before your program is interrupted.
Note that this might not be true for all implementations.
From http://en.cppreference.com/w/cpp/io/manip/endl
In many implementations, standard output is line-buffered, and writing '\n' causes a flush anyway, unless std::ios::sync_with_stdio(false) was executed.
Quote from the same book page 26:
Buffer A region of storage used to hold data. IO facilities often store input (or out-put) in a buffer and read or write the buffer
independently from actions in the program. Output buffers can be
explicitly flushed to force the buffer to be written. Be default,
reading cin flushes cout; cout is also flushed when the program ends
normally.

Why does my code terminate without explanation?

I'm learning c++ again after having not touched it for the last few years, and I've run into a rather peculiar bug that I can't seem to figure out.
When I run the code below, it will accept 10 inputs as I expect it to, but immediately after the first for loop, the program exits. I have run it ingdbto try and figure out the issue, but it reported that the process 'exited normally'.
I compiled using g++ -std=c++11
#include <iostream>
#include <string>
using namespace std;
int main() {
//User inputs
string input[10];
//Get the inputs
for(int i = 0; i < 10; i++) {
//Get this input
printf("%i> ", i);
getline(cin, input[i]);
}
//The application does not make it to this point
//Collected
printf("Thank you for submitting your data.\n");
//Print inputs
for(int a = 0; a < 10; a++) {
//Show the input
printf("%i> %s\n", a, input[a].c_str());
}
}
Based on what you're describing, it sounds like stdout is not being flushed before the program ends. That's unusual; normally, stdout is automatically set up for line-buffered operation in which case it will be flushed as soon as a newline is encountered.
Your best bet is to follow #NathanOliver's advice and use cout << ... rather than printf. The printf command is a throwback to C, and you're using a C++ compiler and C++ features. In fact, you're not even including the header that's usually required for printf, so I'm a little surprised it even compiles.
FWIW, if you choose to continue using printf maybe try manually flushing stdout at the end like so:
fflush(stdout);
Your application does what is supposed to do:
Application will pause at getline() (10 times) (because getline is blocking execution), then it will do some for loops, print something and end (probably closing console window). If you add something at the end to block execution (such as cin.get(), which waits for enter key press) you will see results (because application won't terminate). If you run your code somewhere where output is not removed after program has ended you will see what was printed.

CPP printf giving no output on VS2012

I am using Microsoft Visual Studio 2012 Professional. I have a simple CPP code:
#include "stdio.h"
int main () {
int a = 0, b = 0, c = 0;
printf("\nEnter two numbers:\n");
scanf("%d %d", &a, &b);
c = a+b;
printf("\nc = %d", c);
return 0;
}
The problem I am facing is that the first printf statement is getting printed but the second one is not. The code is exiting without printing anything. However when I debug using breakpoints, the value of c is getting stored in it.
I'll take a wild guess and say you run this from your IDE.
It does print the output. But the program then ends. And it ends so fast, you cannot see the output. If you want your program to wait for you to see it, you will need to find a way to make it wait. For example with another scanf line.
As there is no standard, environment agnostic way to say "Press any key to continue", have a look here for some alternatives.
Add \n to the end of the last printf. It is implementation-defined whether the last line of output to stdout actually gets flushed , if it doesn't end in a newline.
When you use
scanf("%d %d", &a, &b);
then you should give 2 inputs separated by space or enter
scanf("%d,%d", &a, &b);
then you should give 2 input separated by comma(,).
and at last use
printf("Press any key to continue.."); getche(); instead of return;

C/C++ : Can I keep the cursor in the current line after pressing ENTER?

I would like to ask if there's any way to keep the cursor in the current line after pressing ENTER !!
for example ...
#include<stdio.h>
int main()
{
int d=0;
printf("Enter a number : ");
scanf("%d",&d);
if(d%2)printf(" is a Odd number\n");
else printf(" is a Even number\n");
return 0;
}
An example of output :
Enter a number : 10
is a Even number
... but what I need is something like that :
Enter a number : 10 is a Even number
I want to put "is a Even number" (or " is a Odd number") next to the number entered by user
The user is pressing enter, and this is being echoed back and starting a new line.
In order to avoid this, you'll need to turn off echo (and then read and echo individual characters except for newline). This is system-dependent, for example on Linux you can put the tty into raw/uncooked mode.
You may find a library such as GNU readline that does most of the work for you.
The simple answer is "you can't". There is no standard C++ functions to control this behaviour, or to read data without hitting enter at the end (in fact, the data hasn't really been "entered" until you hit enter, so the program won't see the data).
You can use non-standard functionality, such as additional libraries, such as a "curses" library or system dependent code, but we would then have to produce the code to read characters one at a time and merge it together using code that you write.
I would suggest that you use the "repeat the input in the output", and simply do something like this:
printf("%d is", d);
if (d%2)
printf("an odd number\n");
else
printf("an even number\n");
Set up raw keyboard mode and disable canonical mode.
That's almost, how linux manages not to show password chars in terminal.
Termio struct is the thing you should google for.
One link is :
http://asm.sourceforge.net/articles/rawkb.html
The Constants of the assembly are also available for a syscall ioctl.
This trick may help, if you have a vt100-style terminal: cursor movements.
\033 is ESC, ESC + [ + A is cursor up, ESC + [ + C is cursor right
int main()
{
int d=0;
printf("Enter a number : ");
fflush(stdout);
scanf("%d",&d);
printf("\033[A\033[18C%d is a an %s number\n", d, d%2 ? "odd" : "even");
return 0;
}
not with printf and scanf... have you tried with getc() and ungetc(char) ?
OR, try to play with printf("%c", (char)8); if I remember correctly that's a backspace
otherwise, you'll probably have to use some output lib such as ncurses