Here is a code snippet I have written using c++ in turbo C++ IDE. The problem I am facing is after using gets(), cin is not working as it is skipping the inputs.Can someone possibly provide a solution to this issue.
Here is the code snippet :-
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int Resc()
{
char fName[10],lName[10],addr[100],usr[70],pass[20];
int d,y,m;
unsigned int phNo;
char *Gend;
clrscr();
cout<<"Enter First Name :"<<endl;
gets(fName);
cout<<"Enter Last Name :"<<endl;
gets(lName);
cout<<"Enter Gender :"<<endl;
gets(Gend);
cout<<"Enter Address:"<<endl;
gets(addr);
cout<<"Enter Date Of Birth (d/m/y):"<<endl;
cin>>d>>m>>y;
cout<<"Enter Phone Number :"<<endl;
cin>>phNo;
cout<<"Enter Username:"<<endl;
gets(usr);
cout<<"Enter Password:"<<endl;
gets(pass);
getch();
return 0;
}
It would be a great help. Thanks.
Turbo-C++ is ancient. There are free compilers available that are much better. Though I realize that in some countries, unfortunately it is still required by educators. However, if there is any way you can use an alternative, you should. The code you are learning to write right now won't compile on compilers actually used in the industry. This will cause problems for you in future jobs.
gets is the worst function ever to make it into a language standard library. It is impossible to use correctly. Don't ever use it. Excise its existence from your mind.
Don't mix C and C++ I/O. It leads to tricky issues where they get out of sync. Use one or the other, exclusively. If you use C I/O, use scanf and fgets with stdin, not gets. If you use C++ I/O, use cin exclusively. Note that parsing a "d/m/y" date with cin is a bit tricky. On the other hand, using cin would allow you to use string instead of character arrays, which would be infinitely superior. (For example, it would mean you can enter names longer than 9 characters without making your program do weird things.)
Gend should probably be a single char instead of a pointer pointing at nothing. This part of your program is just wrong and extremely likely to misbehave or crash.
Phone numbers are not integers. They often start with zeros, in typical usage contain punctuation and whitespace, and are long enough to overflow an unsigned int. (The moment you use an area or carrier prefix, the integer interpretation is likely more than 4000000000.) Use strings to store phone numbers, always.
Basically, gets() is not a C++ function (it is there because the whole C library is available to C++)
The thing is that you are messing usage of buffered input (using stdio package) with buffered C++ input system. And buffers hit to each other.
Don't mix stdio and c++ buffered I/O systems, as you'll get this kind of problems. What's happening inside of Turbo C++'s implementation is far from being able to check, as 1) you haven't disclosed which TC++ version you are using and 2) I have no such compiler at hand to make tests.
Related
What is the significance of including
ios_base::sync_with_stdio(false);
cin.tie(NULL);
in C++ programs?
In my tests, it speeds up the execution time, but is there a test case I should be worried about by including this?
Do the 2 statements always have to be together, or is the first one sufficient, i.e., ignoring cin.tie(NULL)?
Also, is it permissible to use simultaneous C and C++ commands if its value has been set to false?
https://www.codechef.com/viewsolution/7316085
The above code worked fine, until I used scanf/printf in a C++ program with the value as true. In this case, it gave a segmentation fault. What could be the possible explanation for this?
The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.
ios_base::sync_with_stdio(false);
This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.
Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).
cin.tie(NULL);
This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.
By default cin is tied to cout to ensure a sensible user interaction. For example:
std::cout << "Enter name:";
std::cin >> name;
If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).
So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.
In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.
This is to synchronize IOs from C and C++ world. If you synchronize, then you have a guaranty that the orders of all IOs is exactly what you expect. In general, the problem is the buffering of IOs that causes the problem, synchronizing let both worlds to share the same buffers. For example cout << "Hello"; printf("World"); cout << "Ciao";; without synchronization you'll never know if you'll get HelloCiaoWorld or HelloWorldCiao or WorldHelloCiao...
tie lets you have the guaranty that IOs channels in C++ world are tied one to each other, which means for example that every output have been flushed before inputs occurs (think about cout << "What's your name ?"; cin >> name;).
You can always mix C or C++ IOs, but if you want some reasonable behavior you must synchronize both worlds. Beware that in general it is not recommended to mix them, if you program in C use C stdio, and if you program in C++ use streams. But you may want to mix existing C libraries into C++ code, and in such a case it is needed to synchronize both.
It's just common stuff for making cin input work faster.
For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.
The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).
Using ios_base::sync_with_stdio(false); is sufficient to decouple the C and C++ streams. You can find a discussion of this in Standard C++ IOStreams and Locales, by Langer and Kreft. They note that how this works is implementation-defined.
The cin.tie(NULL) call seems to be requesting a decoupling between the activities on cin and cout. I can't explain why using this with the other optimization should cause a crash. As noted, the link you supplied is bad, so no speculation here.
There are lots of great answers. I just want to add a small note about decoupling the stream.
cin.tie(NULL);
I have faced an issue while decoupling the stream with the CodeChef platform. When I submitted my code, the platform response was "Wrong Answer" but after tying the stream and testing the submission. It worked.
So, If anyone wants to untie the stream, the output stream must be flushed.
As a competitive programmer, I've always used ios::sync_with_stdio(0); to speed up cin and cout. But I've also seen other people use optimizations like cin.sync_with_stdio(0); or cout.sync_with_stdio(0);. For example, the latter two were used in this website: https://usaco.guide/general/fast-io?lang=cpp.
I know that ios::sync_with_stdio(0); unsyncs iostream(cin and cout) from stdio(scanf and printf), so why would someone unsync only the input cin or only the output cout when doing competitive programming (which usually has a large amount of both input and output)?
sync_with_stdio is a static method, cin.sync_with_stdio(0) does "exactly" the same as ios::sync_with_stdio(0);.
Not really exactly as it odr-uses std::cin but it is no-op.
What is the significance of including
ios_base::sync_with_stdio(false);
cin.tie(NULL);
in C++ programs?
In my tests, it speeds up the execution time, but is there a test case I should be worried about by including this?
Do the 2 statements always have to be together, or is the first one sufficient, i.e., ignoring cin.tie(NULL)?
Also, is it permissible to use simultaneous C and C++ commands if its value has been set to false?
https://www.codechef.com/viewsolution/7316085
The above code worked fine, until I used scanf/printf in a C++ program with the value as true. In this case, it gave a segmentation fault. What could be the possible explanation for this?
The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.
ios_base::sync_with_stdio(false);
This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.
Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).
cin.tie(NULL);
This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.
By default cin is tied to cout to ensure a sensible user interaction. For example:
std::cout << "Enter name:";
std::cin >> name;
If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).
So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.
In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.
This is to synchronize IOs from C and C++ world. If you synchronize, then you have a guaranty that the orders of all IOs is exactly what you expect. In general, the problem is the buffering of IOs that causes the problem, synchronizing let both worlds to share the same buffers. For example cout << "Hello"; printf("World"); cout << "Ciao";; without synchronization you'll never know if you'll get HelloCiaoWorld or HelloWorldCiao or WorldHelloCiao...
tie lets you have the guaranty that IOs channels in C++ world are tied one to each other, which means for example that every output have been flushed before inputs occurs (think about cout << "What's your name ?"; cin >> name;).
You can always mix C or C++ IOs, but if you want some reasonable behavior you must synchronize both worlds. Beware that in general it is not recommended to mix them, if you program in C use C stdio, and if you program in C++ use streams. But you may want to mix existing C libraries into C++ code, and in such a case it is needed to synchronize both.
It's just common stuff for making cin input work faster.
For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.
The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).
Using ios_base::sync_with_stdio(false); is sufficient to decouple the C and C++ streams. You can find a discussion of this in Standard C++ IOStreams and Locales, by Langer and Kreft. They note that how this works is implementation-defined.
The cin.tie(NULL) call seems to be requesting a decoupling between the activities on cin and cout. I can't explain why using this with the other optimization should cause a crash. As noted, the link you supplied is bad, so no speculation here.
There are lots of great answers. I just want to add a small note about decoupling the stream.
cin.tie(NULL);
I have faced an issue while decoupling the stream with the CodeChef platform. When I submitted my code, the platform response was "Wrong Answer" but after tying the stream and testing the submission. It worked.
So, If anyone wants to untie the stream, the output stream must be flushed.
This is a very simple question, but unfortunately, I am stuck and do not know what to do. My program is a simple program that keeps on accepting 3 numbers and outputs the largest of the 3. The program keeps on running until the user inputs a character.
As the tittle says, my question is how I can make this execute faster ( There will be a large amount of input data ). Any sort of help which may include using a different algorithm or using different functions or changing the entire code is accepted.
I'm not very experienced in C++ Standard, and thus do not know about all the different functions available in the different libraries, so please do explain your reasons and if you're too busy, at least try and provide a link.
Here is my code
#include<stdio.h>
int main()
{
int a,b,c;
while(scanf("%d %d %d",&a,&b,&c))
{
if(a>=b && a>=c)
printf("%d\n",a);
else if(b>=a && b>=c)
printf("%d\n",b);
else
printf("%d\n",c);
}
return 0;
}
It's working is very simple. The while loop will continue to execute until the user inputs a character. As I've explained earlier, the program accepts 3 numbers and outputs the largest. There is no other part of this code, this is all. I've tried to explain it as much as I can. If you need anything more from my side, please ask, ( I'll try as much as I can ).
I am compiling on an internet platform using CPP 4.9.2 ( That's what is said over there )
Any sort of help will be highly appreciated. Thanks in advance
EDIT
The input is made by a computer, so there is no delay in input.
Also, I will accept answers in c and c++.
UPDATE
I would also like to ask if there are any general library functions or algorithms, or any other sort of advise ( certain things we must do and what we must not do ) to follow to speed up execution ( Not just for this code, but in general ). Any help would be appreciated. ( and sorry for asking such an awkward question without giving any reference material )
Your "algorithm" is very simple and I would write it with the use of the max() function, just because it is better style.
But anyway...
What will take the most time is the scanf. This is your bottleneck. You should write your own read function which reads a huge block with fread and processes it. You may consider doing this asynchronously - but I wouldn't recommend this as a first step (some async implementations are indeed slower than the synchronous implementations).
So basically you do the following:
Read a huge block from file into memory (this is disk IO, so this is the bottleneck)
Parse that block and find your three integers (watch out for the block borders! the first two integers may lie within one block and the third lies in the next - or the block border splits your integer in the middle, so let your parser just catch those things)
Do your comparisions - that runs as hell compared to the disk IO, so no need to improve that
Unless you have a guarantee that the three input numbers are all different, I'd worry about making the program get the correct output. As noted, there's almost nothing to speed up, other than input and output buffering, and maybe speeding up decimal conversions by using custom parsing and formatting code, instead of the general-purpose scanf and printf.
Right now if you receive input values a=5, b=5, c=1, your code will report that 1 is the largest of those three values. Change the > comparisons to >= to fix that.
You can minimize the number of comparisons by remembering previous results. You can do this with:
int d;
if (a >= b)
if (a >= c)
d = a;
else
d = c;
else
if (b >= c)
d = b;
else
d = c;
[then output d as your maximum]
That does exactly 2 comparisons to find a value for d as max(a,b,c).
Your code uses at least two and maybe up to 4.
For example, if i input characters greater than 10 why doesn't it throw an exception or error?
would you get the input with getline instead?
int main()
{
char c[10];
while (cin >> c)
{
cout << c << endl;
}
}
Why doesn't it throw an exception or error?
A buffer overflow is an example of undefined behavior. The behavior is literally undefined: if you overflow a buffer, there are no guarantees whatosever about what your program will do. This doesn't generate an exception because doing so would require lots of relatively costly checks even in correct code, and in C++ the general philosophy is that you don't pay for what you don't need.
If you avoid raw arrays and raw (non-smart) pointers and use the C++ Standard Library containers, strings, and algorithms, you can easily avoid most situations that would result in a buffer overflow.
Would you get the input with getline instead?
You can either use std::getline, which allows you to extract a "line" of characters into a std::string, or you can use >> and extract into a std::string object directly, depending on what, exactly, you want to extract.
there are tools which attempt to expose these issues. valgrind and GuardMalloc are examples of this. as well, msc allows you to specify build options which can expose such issues.
note also that different compilers emit different instructions based on your program, and different instructions when optimizing or not. this means the consequences may exist in some builds, and may not exist in others.
i occasionally test my programs using the tools/techniques i've mentioned. i also use more dynamic allocations in unit tests, in order to expose failure cases more easily when running programs with these tools.
if you're coming from java or another language which integrates smarter arrays: that's not how c programs are interpreted by the compiler, nor is it how they are represented in memory. instead, we typically use proper containers in c++. these will detect many of these issues. for example, a std::vector may throw if you attempt to access an invalid element.
good luck