Why does trying to input two strings using cin.get() fails? I can successfully read the first string but the input fails for second string and subsequent operations.. See the code:
#include <iostream>
#include <stdlib.h>
int main(){
long int n,k;
char a[11],b[11];
cin.get(a,11);
n = atoi(a);
cin.get(b,11);
cout<<b;
k = atoi(b);
cout << "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good() << endl << endl;
}
I am trying to input two strings and store them into long int variables as shown in program, but the cin.get(b,11) fails and stack overflow occurs for
k= atoi(b) .Also, you may observe nothing is output for cout<<b .. And, at last cin.fail() is set to 1 , which means I am doing some kind of logical error.. Please help me in rectifying this!
Please suggest some method which is fast and meant for c++ only ..
(If you feel this question is too bad please mention in comments before down voting this, I am already struggling at 21 rep!)
\n will remain in the buffer after the first cin. You can solve this problem by adding an empty cin.get()
cin.get(a,11);
n = atoi(a);
cin.get();
cin.get(b,11);
cout<<b;
k = atoi(b);
cin.get() Does not extract the delimiter from the input (documentation).
If you are C++ with streams it makes sense to use the built in functionality. In particular, C++ offers formatted I/O. To read two numbers you should use:
long int a, b;
cin >> a;
cin >> b;
This will read two numbers from the standard input.
If speed is a concern, try to turn off C I/O synchronisation: std::ios::sync_with_stdio(false); There is an interesting benchmark here that shows that if you turn of synchronisation with C I/O, streams are actually pretty fast.
Related
I am right now learning about making a program using Borland, so this is my first time on use it. I got confused by the result, cause the result is not what I expected.
Below is my code:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char nama[25];
char kelas[5];
char jurusan[30];
char universitas[30];
char alamat[30];
cout<<"Masukkan Nama Anda\t : ";
gets(nama);
cout<<endl;
cout<<"Kelas\t\t\t : ";
gets(kelas);
cout<<endl;
cout<<"Jurusan\t\t\t : ";
gets(jurusan);
cout<<endl;
cout<<"Universitas\t\t : ";
gets(universitas);
cout<<endl;
cout<<"Alamat\t\t\t : ";
gets(alamat);
cout<<endl;
cout<<"\n\tBIODATA ANDA SEBAGAI MAHASISWA ADALAH SEBAGAI BERIKUT:"<<endl;
cout<<"\n\nNama\t\t\t : "<<nama<<endl;
cout<<"Kelas\t\t\t : "<<kelas<<endl;
cout<<"Jurusan\t\t\t : "<<jurusan<<endl;
cout<<"Universitas\t\t : "<<universitas<<endl;
cout<<"Alamat\t\t\t : "<<alamat<<endl;
cout<<"\n\nSilahkan tekan tombol ENTER untuk keluar dari program biodata singkat ini!";
getch();
}
The result I got is kinda fine, but there is still one problem that I got here. Which there is one variable that don't show what the value of the user already gave, it did not show the value, it even just gave the word "u" which I don't understand from where this word was coming. I sent it with my picture, so you can see it.
I hope you would help me, and thank you very much for reading my problem.
All of your input arrays:
char nama[25];
char kelas[5];
char jurusan[30];
char universitas[30];
char alamat[30];
are going to be one continuous block of chars. Your input methods will easily overflow from one array to the next causing all sorts of havoc.
Try using std::string instead and input from std::cin:
std::string nama;
std::string kelas;
std::string jurusan;
std::string universitas;
std::string alamat;
std::cout << "Masukkan Nama Anda\t : ";
std::cin >> nama;
std::cout << std::endl;
std::cout <<"Kelas\t\t\t : ";
std::cin >> kelas;
std::cout << std::endl;
std::cout << "Jurusan\t\t\t : ";
std::cin >> jurusan;
std::cout <<std::endl;
std::cout << "Universitas\t\t : ";
std::cin >> universitas;
std::cout <<std::endl;
std::cout << "Alamat\t\t\t : ";
std::cin >> alamat;
std::cout << std::endl;
After i tried some several suggestion to solve my own problem. Then i wonder, why there is just the variable of Jurusan which contain character that i don't know where it comes from. I tried to see it again, and then i reverse the place of another variable, also i put a comment sign //comment to make it not being seen as a code by machine in front of the Jurusan variable there is no problem anymore. Quite thinking, and then i just tried to count the sum of character in a variable which exactly below the Jurusan variable(Universitas variable), and then i also count the size of that variable(Universitas variable).
After this i just realised if the word "u" which in the variable Jurusan is the rest of the characther which comes from the variable below the Jurusan variable, which variable Universitas.
I am as the user, put the characther greater than the size of Universitas variable. And of course, that is wrong, and a mistake.
I came back to the code, and make the size of the variable Universitas is greater than before, and right now the problem is solved. And you guys can see it in my picture below if that is already succed, you also can compare it with the previous picture that i sent here in the Question section which has problem.
So, thank you guys for you who tried to help me. Cheers!
Introduction
I am trying to code a converter for bin/oct/dec/hex numbers in c++. At first I print a message in a console asking the user to insert the type of conversion he wants to do and, followed by the cin that allows him to enter the conversion and then i ask him for the number followed by the cin that allows him to enter the number.
My problem
My problem is that after the user inserts the conversion, the variable gets printed on the console without me telling it that.
What I've Tried
I looked on the docs and in their example they do it like this:
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
And that is similar to my code(which you will see below).
I also tried to do getline(cin, type) but still the variables would get printed without me coding that.
My code
Faulty code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string type;
int n;
cout << "Insert what type of conversion you want to make(binoct, bindec, binhex, octbin, octdec, octhex, decbin, decoct, dechex, hexbin, hexoct, hexdec): ";
cin >> type;
cout << "Insert the number you want to convert: ";
cin >> n;
return 0;
}
Input
binoct
1001
Output
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
binoct
Insert the number you want to convert:1001
1001
Expected output:
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
Insert the number you want to convert:1001
Additional notes
I should mention that before this version of the code I did use cout to print my variables to see if it works but i re-built the code a few times and now there's no cout << type or cout << n inside my code
I looked on stackoverflow and I didn't seem to see anything similar, if this is a duplicate I apologize.
The code is fine, either clean and rebuild your project, or it has something to do with your project / debug settings, that print out the value.
Try Building and Running the Program in release mode.
Here is an example code demonstrating the problem I'm facing.
#include <iostream>
#include <string>
extern "C" {
#include <unistd.h>
}
int main()
{
std::cout << "Making tests ready!" << std::endl;
std::cout << "\nTo start out, Enter an integer: ";
int a = 0;
std::cin >> a;
std::string input;
sleep(3); // what to do if user enters data during this?
std::cout << "\n Now enter a string";
std::getline(std::cin, input);
std::cout << "\nHere are your values - " << a << " & " << input;
return 0;
}
See the sleep call in between the code? This could be replaced with somewhat long delays while computing something when my program isn't accepting any inputs. Now if user presses some keys during this time, that input is captured by std::getline() in next line of code. I know this is the default behavior since it should capture the input being provided.
But what I want is to clear all that captured input and start fresh with 15th line that is std::cout << "\n Now enter a string";, which is immediately after sleep. I don't know exact term to describe this or else I would have used that. Thanking you.
Edit: I've tried using std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); in my code, but it asks for input and then discards it.
Please mind my english, not a native speaker.
Reading the comments causes me to think that you can't really solve this problem (at least by the means suggested there). There's an inherent race condition in any case. Consider the following lines:
sleep(3);
// (*) <- Potential location 1.
std::cout << "\n Now enter a string";
// (**) <- Potential location 2.
std::getline(std::cin, input);
The various comments show some (very technically-competent) ways to flush the standard input. The problem is, you cannot put them in the location marked (*) nor (**).
First location - you clear the standard input some way. Now you decide it's time to move to the next line (std::cout << ...). While you do that, the user types in some more input. Race!
Second location - You print out the message (std::cout << ...), and proceed to clear the standard input. Before you manage to do that, the user typed in something. Race!
It seems to me that any of the techniques described in the comment require locking the standard input, and I don't think there's a (standard) way to do so.
While reading this question, I found in the answers different way of reading an integer. Here are two of them.
The one from πάντα ῥεῖ's answer:
if(iFile) {
iFile >> int1;
cout << "From first file:" << int1 << endl;
}
The one from JRowan's answer:
if(!iFile.eof()){
iFile >> int1;
cout << "From first file:" << int1 << endl;
}
But I was wondering if using the code below is equivalent to the two above? Also, is there any reason not to use one of the three sample codes?
if (iFile >> int1) {
cout << "From first file:" << int1 << endl;
}
Thanks.
On constructing the ifstream object iFile, you should check that there were no errors. This is correctly accomplished by simply doing if(iFile) in both C++ and C++11. Assuming you have already done this check, the third code snippet is the only correct way of reading the ints from file. The first two methods will end up printing the last integer before eof twice. This is because they don't check the state of the stream after doing iFile>>int1. So, if they had encountered eof, you wouldn't know and continue to call cout.
The third code is "less protected". It tries to read and if it can, it outputs the result. Meanwhile, the first one verifies if the reference to the file isn't null before trying to read and the second one verify if it has some data or it is just EOF.
The better option for you to use in case you want to read a file completely is to:
if(iFile){
while(!iFile.eof()){
iFile >> int1;
cout << "Number read: " << int1 << endl;
}
}
Excluding those cases that is just a matter of how you want to write your code.
I'm still very new to C++ still and decided to make a fibonacci sequence. It worked (Woo!) but it doesn't work as well as I would like it to.
what I mean by that is say for example I told my program to count the first 10 terms of the sequence I will get
"0, 1, 1" and then I have to press enter for each additional number until it hits ten in which case the program returns 0 and ends.
How do I get the program to display all the numbers I want to without hitting enter for each additional one?
Here is my script:
#include <iostream>
using namespace std;
int main()
{
int FibNum;
cout << "How many numbers of the Fibonacci Sequence would you like to see? \n\n";
cin>> FibNum;
cin.ignore();
int a = 0;
int b = 1;
int c = 2;
cout << "Fibonacci Sequence up to " << FibNum << " terms.\n\n";
cout << a << "\n" << b << "\n";
for (int c = 2; c < FibNum; c++) {
int d = a + b;
cout << d;
cin.ignore();
a = b;
b = d;
}
}
Thanks in advance for any help!
P.s. Also if you notice anything terrible I'm doing please feel free to correct me, I'm very aware I'm probably doing a lot wrong, I'm just trying to learn. :]
A few things:
1) Remove int c = 2; as you're re-defining c inside the for loop.
2) Drop the line cin.ignore();: in your for loop: that will fix your "enter" problem; that line waits for some input then ignores it.
3) Put some white space in your output: e.g. cout << d << ' ' so your numbers are separated.
4) [Acknowledge vincent_zhang] Consider moving to uint64_t as your data type for a, b, and d. This is a standard type in C++11. It's a 64 bit unsigned integer type; adequate for a large number of terms.
and a small thing, bordering on personal opinion,
5) Use ++c instead of c++ as the former will never run slower as, conceptually at least, post-increment has to take a copy of the original value.
Besides the previous answers,
To better format the output, add white space by changing this
cout << d;
to
cout << d << " ";
You may want to change the type of a, b and d from int to double to prevent overflow.
(If you let FibNum=100 in your code, you should be able to observe overflow, meaning that you are going to get some incorrect numbers toward the end of the sequence.)
Move cin.ignore() out of the loop then you dont need to enter to print all the 10 numbers of Fibonacci series