First of all thanks for answering and helping out...
Now i was making a program to let the user enter any number... and then use the program to point out the total number of 4's in the the number entered and i have now encountered a problem..
This is my first post here so please excuse me if i make any mistakes..
The Code
int main()
{
int T,i,j,l;
char N,p[10];
cin>>T;
while(T--) //The number of times a user can enter a new number
{
cout<<"\nEnter Numbers\n";
l=0;i=0;
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!=' '); //Now here between '' something has to be present so that the loop
//terminates as soon as the enter key is pressed right now as soon
//as the spacebar is hit the loop will terminate.
cout<<"\n";
j=0;
for(i=0;i<l;i++) //using l so that the loop runs accordingly
{
if(p[i]=='4')
{
j++; //for couting the number of 4's
}
cout<<p[i]<<"\n"; //wont be needing in the final program but here cout is just
// to check the output
}
cout<<"\n THERE ARE "<<j<<" FOURS\n";
}
}
Please not that i already have a solution for my program so please DO NOT provide a different code using some different logic... i really need this very same program to work.i know that this program can be made to work using string length but here i want the loop to terminate after the enter key is pressed.
Well if you want to stop getting input when the user presses enter instead of space you need to test against '\r', '\n' or '\r\n' depending on what OS you are using. That said you really should be using standard C++ if you are going to use C++. You could easily make your code like:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int loops;
std::cout << "How many numbers to check: ";
std::cin >> loops;
std::cin.get(); // eat newline
for (int i = 0; i < loops; i++)
{
std::string numbers;
std::cout << "Enter numbers and press enter: ";
std::getline(std::cin, numbers);
auto numberOf4s = std::count(numbers.begin(), numbers.end(), '4');
std::cout << "Number of 4's entered: " << numberOf4s << std::endl;
}
return 0;
}
Live Example
You can to see check if N is equal to '\r'. So your while loop looks like
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!='\r');
Related
I am learning C++, and I am doing some exercises in the book I am using. One of them asks to write a program that asks a user how many numbers they want to add up. Then prompt for the numbers the user wants to add or to enter '|' once finished. The numbers are then pushed into a vector. Part of the program asks to check if the size of the vector is equal to the original number of input items and that is where I keep getting an error.
cout << "Please enter the numbers and | once you are done: ";
while(true)
{
for(int num; cin >> num; )
{
if(num == '|')
{
break;
}
ints.push_back(num);
}
if(ints.size() != n)
{
cout << "There are more or less numbers in the vector than originally specified\n"
<< "Vector will be cleared; please re-enter the values: ";
ints.clear();
continue;
}
else
{
break;
}
}
The problem is that if the number of input is off, the message goes into an infinite loop and I am not sure how to fix it.
EDIT: n is the variable that holds in the number of values user wanted to enter.
Thanks!
num is an integer and cin >> num won't extract | symbol. Comparison num == '|' may not work as expected because num could have the numeric value of | ascii symbol even when user did not input any | symbol. You should properly handle end marker reading:
// loop will break when user enters `|` because it is not an integer
// setting failbit of cin
for(int num; cin >> num;)
{
ints.push_back(num);
}
cin.clear(); // reset failbit making cin able to read again
// check the end marker entered by user
{
string end_marker;
cin >> end_marker;
if("|" != end_marker)
{
// use of endl will flush the stream ensuring that
// printed text won't stuck in the buffer
cout << "Please use | as end marker" << endl;
continue;
}
}
Here is how I implemented it. I am worried about the logic in your while loop. I had been taught to avoid while(true) whenever possible. You know the logic behind how your code should work. With more practice you'll start to recognize the conditions you need to use. I am sure there are better ways to do it. But this is the way I tried it.
But to answer your question, the main reason it is failing is because integers cannot compare themselves with characters.
if(num == '|')
That does not work since num is an integer and not a character.
Normally I would implement this in a class and since global variables are not highly looked upon I created my own namespace. You'll have to finish the rest of the logic yourself however:
#include <iostream>
#include <vector>
#include <string>
namespace global
{
std::vector<std::string> strings;
std::vector<int> ints;
std::string a = " ";
int num = 0;
}
void doWork()
{
std::cout << "Please enter the number of integers you would like to add up: ";
std::cin >> global::num;
std::cout << "Please enter the numbers and | once you are done: ";
while (global::a != "|")
{
std::cin >> global::a;
global::strings.push_back(global::a);
}
global::strings.pop_back();
for(auto &e : global::strings)
{
global::ints.push_back(std::stoi(e));
}
}
int main()
{
doWork();
if(global::ints.size() != global::num)
{
std::cout << "Size of vector does not match the size specified. Clearing vector" << std::endl;
global::ints.clear();
global::strings.clear();
global::num = 0;
global::a = " ";
doWork();
}
}
I made a vector of char's and converted those into integers so that way you could add them up. The while loop should be checking for | rather than always running true. It then will check the size of the vector in the end, clear it if it does not match, and ask you to do it again. This is the best way that I could think of doing it.
EDIT: as VTT pointed out, char can only do one character at a time. I have converted it into a string in order to handle the conversion.
EDIT 2: reset the values of global::num and global::a to their default at the end of the failure in order to prevent crashing.
For a program I'm writing, I wish to read in characters from the keyboard using cin until a certain amount of time has passed. The user can enter as many character as they wish (from 0 to however many possible), and the program needs to store the characters in an array for use later. Ideally, the user should not have to press enter after each letter; the program should be able to read in the input without any line breaks and stop once the specified time is up. I've been looking for a while and have tried different methods, including using getline, usleep, and even SDL, but nothing I've tried has worked. This is my latest attempt:
#include <iostream>
using namespace std;
#include <time.h>
const float frame_length = 1;
int main () {
char test[40];
clock_t t;
t = clock();
int counter = 0;
while (clock() - t < (1000000 * frame_length)){
cin >> test[counter];
counter ++ ;
}
cout << endl << "STOP" << endl;
}
The problem here is that the loop is not stopping after the specified time at all (when I replaced the cin line with a cout line it did) and the user still needs to press enter every time. Is it at all possible to read in input the way I wish? If it helps, I'm working on a Mac. Any help would be much appreciated.
Since you said deally, the user should not have to press enter after each letter; the program should be able to read in the input without any line breaks, your program will fail to meet above requirements since std::cin blocks the current thread till user hit the ENTER key. what you can do is constantly monitor the key states. if a key has pressed in a given time add that character to your test array. if you are in windows environment, you can use GetAsycKeyState function for this purpose.
Here is a modified code,
#include <iostream>
#include <Windows.h>
#include <time.h>
const float frame_length = 1;
using namespace std;
int main () {
char test[40];
clock_t t;
t = clock();
int counter = 0;
while (clock() - t < (3000 * frame_length)){
//cin >> test[counter];
//i have added Sleep(200) here to prevent
//picking up a single key stroke as many key strokes.
Sleep(200);
for(int key = 0x41; key < 0x5a; key++)
{
if(GetAsyncKeyState(key))
{
test[counter] = char(key);
cout << char(key) << endl;
counter ++ ;
break;
}
}
}
cout << endl << "STOP" << endl;
}
Good evening everyone, i am attempting to write code that will determine when a number is largest and smallest.. I have asked some tutors I know for help and they have been stumped on this as well. I can not use functions or arrays or breaks. :/ Which I understand makes the process more difficult.. My professor has stated
"The only decisions staments allowed inside the loop are to determine the largest and smallest value. This means you are not allowed to use a decision to determine if the first number was entered. This is going to require you to prime your loop. We cover priming the loop in the next section but for this assignment it means get the first number before the loop begins. We will also assume that at least one number is going to be input."
I don't understand how he expects us to do something we have not learned yet, but regardless.. This is how far I have gotten on the assignment..
We have to have the user input a value to determine how many values will be input...
I keep receiving an error message after I input how many values I would like to check,
"the variable "num" is being used without being initialized.." But num is in the int!!!
Then have the software basically identify the largest and smallest... Hopefully this makes sense to someone.. If you have any questions, or if I need to clarify anything please let me know, I will do so to the best of my ability..
#include <iostream>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=0;
{ cout << "How many numbers do you want to enter" ;
cin >> number;
for (int i=0; num!=number; i++)
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}
This:
for (int i=0; num!=number; i++)
has undefined behavior, num doesn't have a value when this is first evaluated. You meant i != number (or, even better, i < number).
It would be better to use some other way of stopping, i.e. stop when a non-number is entered for instance.
Update: Just to clarify: there are other issues as well, such as min not being initialized in a way that make as many numbers as possible smaller than it. I would probably have gone for min = INT_MAX; or something like that. See <climits> for that constant.
int min=0;
you should change that to
int min=std::numeric_limits<int>::max();
Otherwise, the if the number you entered is greater than 0, it will not be assigned to min.
the variable "num" is being used without being initialized..
Give num a value, you have not given it a value before your loop starts. But that loop concept itself is wrong, try this.
for (int i=0; i < number; i++)
There is two problem in your code, first your min must be a great number like maximum integer, and the second is your for loop should loop on i. I commented lines that you need to change :)
#include <iostream>
#include <limits>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=std::numeric_limits<int>::max(); // change min to maximum integer possible in c++
{
cout << "How many numbers do you want to enter" ;
cin >> number;
//for (int i=0; num !=number; i++) change this line
for (int i=0; i<number; i++) //to this line
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}
I was learning to push_back vectors in C++, and I got to where I can use it. However, the code I made, pasted below, asks the user every time the loop ends if the user wants to continue the loop or not. I found this very inconvenient, so I wanted to change the code to where when the user inputs ("EXIT"), it would break the for loop. How would I have to change the code in this case?
I pasted the whole code just in case I may have to change the portions besides the for loop.
#define all student_marks.begin(), student_marks.end()
using namespace std;
int main()
{
vector<double> student_marks; //create container
double mark;
char more_students = 'y'; //set default to yes ('y')
while (more_students=='y' || more_students=='Y') {
cout<<"Enter mark for student #"<<student_marks.size()+1<<":";
cin>>mark; //enter mark
student_marks.push_back(mark); //push_back
cout<<"More students?(y/n)";
cin>>more_students; //user selects to break or continue the loop
}
double sum = accumulate(all, 0.0), average = sum/student_marks.size(); //sum and ave
cout<<endl
<<"Total mark:\t\t"<<sum<<endl
<<"Average mark:\t"<<average<<endl
<<"Highest mark:\t"<<*max_element(all)<<endl
<<"Lowest mark:\t"<<*min_element(all)<<endl<<endl;
cout<<"-----Score list-----"<<endl;
sort(all,greater<double>()); //sort list
for (size_t i=0; i<student_marks.size(); i++)
cout<<"#"<<i+1<<". "<<student_marks[i]<<endl; //outputs results as list
return 0;
}
You could just stay in the loop as long as the user inputs valid marks:
cout << "Enter mark for student #1:"
while(cin >> mark) {
students_marks.push_bak(mark);
cout << "Enter mark for student #" << marks.size() + 1;
}
The loop will exit as soon as the user enters something other than a double, e.g. the EOF flag.
The problem is, in C++, I hope to get numbers from user and put every int to an vector. So I write the following code:
#include <iostream>
#include <vector>
using namespace std;
vector<int> readVals()
{
vector<int> read;
int temp;
cin >> temp;
while (!cin.fail() && !cin.eof())
{
read.push_back(temp);
cin >> temp;
}
return read;
}
void printVals(vector<int> v)
{
if(v.size() >= 1)
{
for (vector<int>::size_type i = 0; i < v.size()-1; i++ )
{
cout << v[i] << " ";
cout << v[v.size()-1] << "\n";
}
}
}
int main()
{
vector<int> a = readVals();
printVals(a);
return 0;
}
Then, I compile it to create an a.out file. I have some numbers in in1. And when I do the command: a.out < in1, I got what I want.
But I'm confused when I hope the data can be inputted by user. The user can input some numbers and press Enter to pass the numbers in. However, I used getline(), failed. !="\n", failed. Everytime when I press Enter, it seems that the program is still waiting for more numbers and not print out the result. Does any one can help me to make it successfully? Thank you!
Your loop is waiting for cin to be in a "failed" state or at the end of file. Hitting enter does neither. You can end the input by hitting CTRL-Z on windows or CTRL-D on unix/mac. These send the "End of file" character to cin. Alternatively, change your loop condition to "listen" for some specific input.