Why does cin cause this program to hang? - c++

I have posted the relevant code below. When I compile the program, it runs and reaches the point where it waits for the input. I type in an integer and press ENTER, but the code never continues. How would I go about correcting this?
int i;
cout << "Please input column to sort by: ";
cin >> i;

Well, first of all, what you posted above won't compile. Try this instead:
#include <iostream>
int main(int argc, char *argv[]) {
int i;
std::cout << "Please input column to sort by: ";
std::cin >> i;
std::cout << "You entered: " << i << "\n";
return 0;
}
Compile it with g++ -O3 thefile.cpp, assuming the file is called "thefile.cpp".
If it doesn't work then there is a serious issue going on. If it does you should be able to diagnose your issue further.

If you use visual studio 2010 try this:
#include<iostream>
using namespace std;
int main(){
int i;
cout<<"Please input column to sort by: ";
cin>>i;
cout<<"Your input the number: "<<i<<"\n\n";
system("pause");
return 0;
}

Related

Comparing char array in c++

I need help in c++. I want to compare char array. So, I did some coding. Unfortunately, it always comes out an error. I can't run it. Here I attached the code. Please help me fix this code. I want to check if the conclusion equal to sentence 1 then it is invalid but if it's not equal sentence 1 then it is valid. Help me, please. Thank you.
int number;
char sentence[number];
char rules[50];
char statement[50];
char premis1[100];
char premis2[100];
char conclusion[100];
cout<<"How many sentence you want to insert:";
cin>>number;
cout<<endl;
for(int i=0; i<number; i++)
{
cout<<"Enter sentence ";
cout<<i+1;
cout<<":";
cin>>sentence[i];
cin.ignore();
}
cout<<"Enter premis 1:";
cin.getline(premis1,100);
cin.ignore();
cout<<"Enter premis 2:";
cin.getline(premis2,100);
cin.ignore();
cout<<"Enter conclusion:";
cin.getline(conclusion,100);
cin.ignore();
for(int i=0;i<number;i++)
{
if(strcmp(conclusion,sentence[0],)==0)
{
cout<<"Statement is invalid."<<endl;
cout<<endl;
}
else if(strcmp(conclusion,sentence[0])!=0)
{
cout<<"Statement is valid."<<endl;
}
else
cout<<"exit"<<endl;
}
Your mistakes you've made in the program:
You never initialized number but used in sentence[], still it's invalid even after number's declaration, that's because the compiler must know the exact value of the array length to be defined.
You've defined sentence as a char array but from your code, it seems like you wanted to store a full sentence into each element of array, which is impossible. Use std::string here.
You're doing strcmp() with the first character of char array, not the sentence with conclusion.
Aside: Please don't forget to include the important header files which are common to the code and we must assume your program is incomplete, because it has a lack of main() and statement(s), such as strcmp(...,...',' - incomplete).
Redesigned the program (notice that using namespace std statement is used here because it's just a small program to demonstrate and for sake of simplicity and getting rid of std:: prefixes everywhere):
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(void) {
int number = 0;
vector<string> sentence;
string tempSentence;
string conclusion;
cout << endl;
cout << "How many sentences you want to insert? ";
cin >> number;
for (int i = 0; i < number; i++) {
fflush(stdin);
cout << "Enter sentence " << (i + 1) << ": ";
getline(cin, tempSentence);
sentence.push_back(tempSentence);
}
cout << "Enter conclusion: ";
getline(cin, conclusion);
if (conclusion == sentence[0])
cout << "The statement is invalid." << endl;
else if (conclusion != sentence[0])
cout << "The statement is valid." << endl;
else
cout << "EXIT" << endl;
return 0;
}
I've taken std::vector<> of std::string here to insert a single string in defined number of sentences given in a dynamic way in each iteration (from #include <vector>) and used std::string rather than char arr[], it's easy to compare strings here.
Sample Output:
$ g++ -o prog prog.cpp; ./prog
How many sentences you want to insert? 3 // --- INPUT
Enter sentence 1: This is the first sentence.
Enter sentence 2: This is the second sentence.
Enter sentence 3: This is the third sentence.
Enter conclusion: This is NOT the first sentence.
The statement is valid. // first sentence != conclusion // --- OUTPUT

Testing for an integer in c++

I'm trying to write a c++ program that tests each input integer, and stops if the input is invalid.
Here is my code, without the testing part:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
cin >> i;
cout << endl << i << endl;
} while(i != 0);
system("Pause");
return 0;
}
How can I test the input for validity?
The easiest is to use std::getline to read a whole line of input into a std::string, and then test whether that string is a valid integer specification.
It's also possible to do this by testing the failure state of cin, and clearing it, but that way lies an assortment of complications that you don't want.
In order to test the string you can use a high level std::istringstream (just read from it and test its failure state after) or, more efficient but a little more complicated, strtol from the C library (the latter is what a C++ stream uses internally).
You need to test whether a string is an integer without crashing.
You can do this with strtol(). It converts the string to an integer, and reports on the first character that is not a legal char for a number. No invalid characters means the entire string was an integer.
There is a good description and example of how to use it here:
http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
while(!(cin >> i))
{
cin.clear();
cin.ignore();
cout << "\nInput was invalid, please re-enter: ";
}
cout << endl << "The integer is: " << i << endl;
} while(i != 0);
system("Pause");
return 0;
}

(cin >> int).get() doesn't properly work in Xcode(4.3.3)

I'm currently working on the book "C++ Primer Plus" and doing some of the programming excersis.
As it seems, I'm having a problem with Xcode(4.3.3) because following code doesn't work how it's supposed to work:
#include <iostream>
#include <string>
struct car
{
std::string maker;
int year;
};
int main()
{
using namespace std;
cout << "How many cars do you wish to catalog? ";
int nCars;
(cin >> nCars).get();
car* aCars = new car[nCars];
for (int i = 0; i < nCars; i++)
{
cout << "\nCar #" << (i + 1) << endl;
cout << "Please enter the make: ";
getline (cin, (aCars + i)->maker);
cout << "\nPlease enter the year made: ";
(cin >> (aCars + i)->year).get();
}
cout << "Here is your collection: \n";
for (int i = 0; i < nCars; i++)
{
cout << (aCars + i)->year << " " << (aCars + i)->maker << endl;
}
delete [] aCars;
return 0;
}
The problem is, I don't have the chance to enter any maker. The program directly goes to the point where I have to enter the year, even though I'm using "(cin >> nCars).get();" to get rid of the newline character.
Am I overlooking something?
Thanks in advance!
I suspect that you may be running on windows and the two-byte newlines are hitting you. You may be able to improve things (for lines that aren't ridiculously long) with ignore:
cin >> nCars;
cin.ignore(1024, '\n');
Note that since you rely on stream numeric processing, entering a non-numeric year such as QQ will result in the programming just finishing without asking for any more input.
You don't need to do math on the years so treat them as strings instead of integers. Then if you need to you can do validation of each year after you get the input.
Ok, guys..I found the problem.
The console within Xcode doesn't work as expected when using cin.get().
I tried the same code in the terminal as well as with Visual Studio (Win 7) and the program works perfectly.
Anyway, thank you all for your advices. I'll try consider them the next time. :)
Cheers!

do while loops can't have two cin statements?

I'm just following a simple c++ tutorial on do/while loops and i seem to have copied exactly what was written in the tutorial but i'm not yielding the same results. This is my code:
int main()
{
int c=0;
int i=0;
int str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15);
cout << "The sum of the numbers are: " << c << endl;
system("pause");
return (0);
}
Right now, after 1 iteration, the loop just runs without asking for my inputs again and only calculating the sum with my first initial input for i.
However if i remove the second pair of cout/cin statements, the program works fine..
can someone spot my error please? thank you!
After you read the string with your cin >> str;, there's still a new-line sitting in the input buffer. When you execute cin >> i; in the next iteration, it reads the newline as if you just pressed enter without entering a number, so it doesn't wait for you to enter anything.
The usual cure is to put something like cin.ignore(100, '\n'); after you read the string. The 100 is more or less arbitrary -- it just limits the number of characters it'll skip.
If you change
int str;
to
char str;
Your loop works as you seem to intend (tested in Visual Studio 2010).
Although, you should also probably check for str == 'n', since they told you that they were done.
...and only calculating the sum with my first initial input for i...
This is an expected behavior, because you are just reading the str and not using it. If you enter i >= 15 then loop must break, otherwise continues.
I think you wanted this thing
In this case total sum c will be less than 15 and continue to sum if user inputs y.
#include<iostream>
using namespace std;
int main()
{
int c=0;
int i=0;
char str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15 && str=='y');
cout << "The sum of the numbers are: " << c << endl;
return 0;
}

Why does this cin loop never end?

In the following code, if the user inputs something that is not an int, the program goes into an infinite loop. Why does this happen, and what should I do to fix it?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
char str[100];
while (!(cin >> i))
{
gets(str);
cout << "failure read!" << endl;
}
cout << "successful read!" << endl;
return 0;
}
Clear the error state:
int main()
{
int i;
char str[100];
while (!(cin >> i))
{
cin.clear();
cin.getline(str,100);
cout << "failure read!" << endl;
}
cout << "successful read!" << endl;
return 0;
}
I think that you want to replace the while loop with an if statement, with this loop, you'll continuously read from cin while an error occurs. However, cin is structured so that after an error occurs, you must manually clear the error state, and since you're not doing that here this will go into an infinite loop. Using an if statement tries to read a value and then let's you know whether or not it succeeded.
Additionally, this really isn't a good way to read from cin. It's brittle and any invalid input can totally take down your program, since gets is inherently unsafe. For a discussion of a safer and more robust way to get input in C++, check out http://www.stanford.edu/class/cs106l/course-reader/Ch3_Streams.pdf