I was working on a school project with my friend and we want our program to take integer values from user and store it in a vector as long as the user enter some value and exit the loop for input when user stops inputting numbers.
This was my first sample code which goes on infinitely:
while(cin>>x){
v.push_back(x);
}
There is a condition that the numbers must be greater than one but enter is greater than 0 in integer value so my second code is but it is not working and it also goes on infinitely.
This is my sample code:
while(cin>>x){
if(x<0){
break;
}
else{
v.push_back(x);
}
}
Kindly suggest me a solution thanks in advance :)
Most important part for you is to clearly describe what you want. The program has to have some condition under which it terminates.
Two ideas:
The user enters integer values separated by spaces and then pushes enter
The user enters an integer, presses enter and continues. As soon as he presses enter twice, it terminates.
How to do it:
Simple use cin with a string, delimit by space and then convert to integers.
Use cin with a string but otherwise as you do right now, ask whether the string is "", if not convert to integer.
Not entirely sure but I think you mean something like read the line then extract integers? If so, try something like this - there is no error checking, it will simply discard the everything from the first non-integer. I have left out exceptions and not used and for_each or lambdas or anything fancy. Hopefully will be useful to get you started.
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
std::vector<int> getUserInput(){
std::vector<int> result;
std::string s;
std::getline(std::cin, s);
std::istringstream is(s);
while(is){
int value;
is >> value;
if(is) result.push_back(value);
}
return result;
}
int main(int,char**){
std::vector<int> userValues = getUserInput();
std::cout << "User input values:\n";
for(int value : userValues) std::cout << value << '\n';
return 0;
}
After using Aziuth's suggestion and doing some research on websites like Topcoder and Codechef and other competitive programming websites I think i found a solution without needing to use a string. It takes all the input values until a newline is entered. Thanks a lot everyone for their time and knowledge for this question.
The code is:
while(1){
cin>>x;
v.push_back(x);
char ch = getchar();
if(ch=='\n')
break;
}
Related
this is some code that i have in C++:
#include <iostream>
using namespace std;
int main() {
int num1;
string some;
cout << "enter something";
cin >> num1 >> some;
cout << num1 << endl << some;
return 0;
}
I'm a bit confused about how inputting works exactly in C++. First of all, through observation i figured that when asking for multiple inputs, C++ looks for either space or line separated data and am not sure if that is exactly true as websites i have looked at don't say this explicitly. Also my main problem is what happens when for num1, which is an integer variable, i input 'hello', which is a string, and click enter. In that case, C++ doesn't even ask me for an input for some and instead just outputs 0. I am a beginner in C++ and am very confused why this happens as i would expect an error message instead. I am hoping that someone would explain to me the procedure that C++ goes through when dealing with a situation like this, where a string gets stored in an int variable, to better understand inputting in C++. Thanks!
With "Hello" you are putting the cout and cin into an error state where especially cin doesn't accept any further input.
If you want to prevent the user from writing text instead of numbers, you have to check each input character. There are several functions that can check if a key code equals a number or not.
I would like to know if it's possible to have multiple while (cin>>(variable)) as in the following code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1, v2;
int input;
while (cin>>input)
v1.push_back(input);
while (cin>>input)
v2.push_back(input);
return 0;
}
The logic of my program is to let user define the number of elements and value of each element in two sets of int vectors.
However, I realized that after entering the first set of numbers for the first vector (ending with an EOF), I'm unable to enter the second set of numbers for the second vector and the program terminates promptly. I suspect that EOF meant for the first cin for the first vector was processed by the second cin for the second vector as well.
Is there any way for the program above to run correctly i.e. having more than one while (cin)?
When you do while (cin>>input) you are effectively asking the input stream cin to produce integers until the stream has gone bad (i.e. an EOF was encountered, the steam was unable to convert the user's input to an integer, or maybe there was another problem).
After the loop terminates the state of the stream will still be in whatever state caused it to stop the loop. In order to continue reading from cin until another EOF token is encountered you will need to first clear the eof fail bit, this can be done (as πάντα ῥεῖ points out) by using cin.clear(). However, you should check the state of cin first, in case the input failed for another reason (perhaps the user entered a word instead of a number).
Two options might be: check that only the eof bit was set, or you can only unset the eof bit:
if (cin.eof())
{
std::cout << "Yay, reached an EOF" << std::endl;
}
cin.clear(std::ios_base::eofbit);
You need to call cin.clear(); after it was ended with EOF (i.e. CTRL-D or CTRL-Z), to reuse it again.
This while loop reads until the end of the file has been reached.
There is nothing more after the end, so any further read will fail.
You have to design another way so your program knows (i.e., has a condition) when the first set of numbers has finished.
There are usually two options:
read the number of values first
int count;
std::cin >> count;
for (int i = 0; i < count; i++) {
std::cin >> input;
v1.push_back(input);
}
// read into v2 …
or have a delimiting value, i.e. a special value that is not valid. In this case, I will take negative numbers as invalid.
std::vector<int> *v_input = &v1; // first read to v1
while (std::cin << input) {
if (input >= 0)
v_input->push_back(input);
else {
// invalid value, thus push numbers to the next vector
if (v_input == &v1)
v_input = &v2;
else
// invalid value while reading values for v2 - do not read any more lines
break;
}
}
However, you could also first read whole lines as a string and test, e.g., if the string is empty. If yes, input values to v2 instead of v1. Of the input is not empty, convert to int and push to the current vector.
I would like to know if it's possible to have multiple while (cin>>(variable)) as in the following code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1, v2;
int input;
while (cin>>input)
v1.push_back(input);
while (cin>>input)
v2.push_back(input);
return 0;
}
The logic of my program is to let user define the number of elements and value of each element in two sets of int vectors.
However, I realized that after entering the first set of numbers for the first vector (ending with an EOF), I'm unable to enter the second set of numbers for the second vector and the program terminates promptly. I suspect that EOF meant for the first cin for the first vector was processed by the second cin for the second vector as well.
Is there any way for the program above to run correctly i.e. having more than one while (cin)?
When you do while (cin>>input) you are effectively asking the input stream cin to produce integers until the stream has gone bad (i.e. an EOF was encountered, the steam was unable to convert the user's input to an integer, or maybe there was another problem).
After the loop terminates the state of the stream will still be in whatever state caused it to stop the loop. In order to continue reading from cin until another EOF token is encountered you will need to first clear the eof fail bit, this can be done (as πάντα ῥεῖ points out) by using cin.clear(). However, you should check the state of cin first, in case the input failed for another reason (perhaps the user entered a word instead of a number).
Two options might be: check that only the eof bit was set, or you can only unset the eof bit:
if (cin.eof())
{
std::cout << "Yay, reached an EOF" << std::endl;
}
cin.clear(std::ios_base::eofbit);
You need to call cin.clear(); after it was ended with EOF (i.e. CTRL-D or CTRL-Z), to reuse it again.
This while loop reads until the end of the file has been reached.
There is nothing more after the end, so any further read will fail.
You have to design another way so your program knows (i.e., has a condition) when the first set of numbers has finished.
There are usually two options:
read the number of values first
int count;
std::cin >> count;
for (int i = 0; i < count; i++) {
std::cin >> input;
v1.push_back(input);
}
// read into v2 …
or have a delimiting value, i.e. a special value that is not valid. In this case, I will take negative numbers as invalid.
std::vector<int> *v_input = &v1; // first read to v1
while (std::cin << input) {
if (input >= 0)
v_input->push_back(input);
else {
// invalid value, thus push numbers to the next vector
if (v_input == &v1)
v_input = &v2;
else
// invalid value while reading values for v2 - do not read any more lines
break;
}
}
However, you could also first read whole lines as a string and test, e.g., if the string is empty. If yes, input values to v2 instead of v1. Of the input is not empty, convert to int and push to the current vector.
This may be a total beginner's question, but I have yet to find an answer that works for me.
Currently, I'm writing a program for a class that takes in a user's input (which can be one or more numbers separated by spaces), then determines whether the number is prime, perfect, or neither. If the number is perfect, then it will display the divisors.
Thus far, I've already written the code for the prime, perfect, and listing the divisors. I'm stuck on the input portion of my program. I don't know how to get the input that's separated by spaces to go through my loops one at a time.
This is my current program:
cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin>>num;
while (divisor<=num)
if(num%divisor==0)
{
cout<<divisor<<endl;
total=total+divisor;
divisor++;
}
else divisor++;
if(total==num*2)
cout<<"The number you entered is perfect!"<<endl;
else cout<<"The number you entered is not perfect!"<<endl;
if(num==2||num==3||num==5||num==7)
cout<<"The number you entered is prime!"<<endl;
else if(num%2==0||num%3==0||num%5==0||num%7==0)
cout<<"The number you entered is not prime!"<<endl;
else cout<<"The number you entered is prime!"<<endl;
return 0;
It works, but only for a single number. If anyone could help me to get it to be able to read multiple inputs separated by spaces, it'd be greatly appreciated. Also, just a side note, I do not know how many numbers will be entered, so I can't just make a variable for each one. It will be a random amount of numbers.
Thanks!
By default, cin reads from the input discarding any spaces. So, all you have to do is to use a do while loop to read the input more than one time:
do {
cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin >> num;
// reset your variables
// your function stuff (calculations)
}
while (true); // or some condition
I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.
#include <string>
#include <vector>
...
string rawInput;
vector<String> numbers;
while( getline( cin, rawInput, ' ' ) )
{
numbers.push_back(rawInput);
}
So say the input looks like this:
Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7
You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.
Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.
while(!numbers.empty())
{
string temp = numbers.pop_back();//removes the last element from the string
num = atoi( temp.c_str() ); //re-used your 'num' variable from your code
...//do stuff
}
Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:
#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)
Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/
Edit:
I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].
#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
bool isNum = true;
for(int i = 0; i < rawInput.length() && isNum; ++i)
{
isNum = isdigit( rawInput[i]);
}
if(isNum)
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
else
cout << rawInput << " is not a number!" << endl;
}
The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.
You'll want to:
Read in an entire line from the console
Tokenize the line, splitting along spaces.
Place those split pieces into an array or list
Step through that array/list, performing your prime/perfect/etc tests.
What has your class covered along these lines so far?
int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
cin >> i;
sum += i;
//cout << i << endl;
if (cin.peek() == '\n') {
break;
}
}
cout << "result: " << sum << endl;
return 0;
}
I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints
std::vector<int> num{};
int buf;
do{
std::cin >> buf;
num.push_back(buf);
}while(std::cin.peek() == ' ');
In C language you can to it using scanf like this:
scanf('%d %d',&a,&b);
Hi guys i am new to c++, I just wrote this code to find min/max of a array of numbers.
I just want to know how can I make the no. of entries flexible(I mean the user should be able to enter as many entries as possible without specifying how many in the starting)
Here's the code, but its not working, can someone please help?
Thanks
code:
#include <iostream>
using namespace std;
int main(){
cout<<"Program to calculate max/min/second max\n";
int *A;
A=new int[5];
bool flag=false;
int x=0,i=0;
cout<<"Enter the numbers\n";
do{
cin>>x;
if(x=='\0'){
flag=true;
}
*(A+i)=x;
i++;
}
while(!flag);
for(int j=0;j<i;j++){
cout<<*(A+j)<<"\n";
}
return 0;
}
You are confused that pressing enter will just give you the null terminator. It will not. Depending on your platform it will give you a carriage return/line-feed (\r\n in Win, \n in *ix). The best way to do this is to just have them use a letter like 'q' for quit or a number like -1, and then compare on that.
Dynamic Memory Allocation is a bit of a tricky subject for a beginning programmer (in C and C++ in any case.) The easiest way is to have the user specify how many entries, but you don't want this.
Otherwise using the vector class over an array is probably a better (and easier to grapple with than directly using pointers.)
http://www.cplusplus.com/reference/stl/vector/ is a good place to start. Look at the syntax for creating the vector and the push_back() member function to accomplish your task.
Good Luck,
SegFaults McGee
You will have to use some sort of variable length datastructure and Vector is the best choice for this since you are working in C++. Therefore, instead of your fixed length array:
int *A;
A=new int[5];
use a vector like this:
std::vector<int> input;
And then to add values to this, use the following:
input.push_back(10);
There is an example on this page about using vectors.
mean the user should be able to enter as many entries as possible without specifying how many in the starting
With the above requirement and with the code you have, you can enter no more than 5 elements to an array.
do{
cin>>x;
if(x=='\0'){
flag=true;
}
*(A+i)=x;
i++;
}while(!flag);
Use std::vector instead for the requirement where it implicitly manages memory for you.
If you use
std::vector<int> a;
then the input becomes simply
while (std::cin >> x)
a.push_back(x);
Then the user can press ^D (Unix/Linux/etc) or ^Z (DOS/Win) when they've entered all the numbers, or use the program as in:
echo 1 4 22 | program
program < input_file
If you want to have an empty line denote the end of input, then with input validation:
std::string line;
while (getline(std::cin, line))
{
char c;
std::istringstream iss(line);
int x;
if (iss >> x)
{
a.push_back(x);
char c;
if (iss >> c)
{
std::cerr << "unexpected character '" << c << "' in line '" << line << "', terminating\n";
exit(EXIT_FAILURE);
}
}
else if (!iss.eof())
break; // empty line...
else
{
std::cerr << "unexpected characters in line '" << line << "', terminating\n";
exit(EXIT_FAILURE);
}
}