In the following program if i reverse the order of the two i/o statements,that is,if i enter the number of elements first and after that the string..the command prompt doesnt takes in the string...why is it so?
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <stdio.h>
usingnamespace std;
int main()
{
char arr[10];
int n;
cout<<"Enter string "<<endl;
gets(str);
cout<<"Enter the number of elements"<<endl;
cin>>n;
}
Basically the cin object reads characters until a newline(return/enter) character is reached. So if its not giving you the chance then you might want to ignore any newline character in the buffer using the cin.ignore(); function before reading from the buffer.
Better still why don't you replace the gets() function with the standard cin? as it C++?
Also, there is no need for the <stdio.h> better still <cstdio> header as its C and not C++ -- This should be done after removing the gets() function.
Basically the cin object reads characters until a newline(return/enter) character is reached.
That is not correct. std::cin will not read up until a newline is hit it will read up until the first whitespace is hit. If you want to read up until a newline you should use getline() instead.
As for the OP's question.
Could you explain a bit more about your problem? Not exactly sure what you mean by switching the two IO statements around. Do you mean do this instead?
1 2 3 4
cout<<"Enter the number of elements"<<endl;
cin>>n;
cout<<"Enter string "<<endl;
gets(str);
NOTE: Where is the variable str defined?
Also as Aceix mentioned I would suggest not mixing C and C++ IO operations. If you are going to use C++ might as well use it's IO operations (Specially since you are already for the integer).
Apart from the obvious being that there is a stray newline character still in the input buffer, there is also the case of what happens at runtime when the user of your program decides to enter a string larger than 9 characters (buffer overflow):