user enters String instead of Int [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
We have tried to search this problem but we haven't found any answers. If The user inputs a string variable when the system requires a integer how do you evade the problem with out using a while loop?
{
int grade_var=0,grade_1=0,sum=0;
cout<<"Enter the number of grades you have:\t";
cin>>grade_var;
for(int i=1;i<=grade_var;i++)
I don't wish to do a while loop for my program has a lot of integer insertions and want to know an easier way to correct rather than while loops?

While loops are generally the way to go.
However, to keep the code clean, you may want to consider putting said while loop into a helper function, so you can just call PollForIntegerInput(string prompt) from anywhere in your code, and then handle that input in one place. There is almost never a reason you should be duplicating an input loop like that.
As for a truly nonlooping answer, I have none.

Calling operator>> on a stream returns the stream itself, which can be converted to bool to check if the stream is in a good state. If a bad extraction happens, the stream is not in a good state. So you can do something like this:
if (cin >> grade_var)
This will check that it was successful. You can just negate the condition to find it if it wasn't successful. How you handle this condition is up to. Maybe you'll return early on failure. If you want to reprompt the user for correct input, however, you'll need a loop.

It's not too clear what your problem is, but...
It's almost always poor design to input the number of data
points which will follow. If you expect a series of int, for
example:
std::vector<int> grades;
int grade;
while ( std::cin >> grade ) {
grades.push_back( grade );
}
It doesn't get much simpler.
If you do want to insist on an exact number of input, outputting
an error when the user inputs something incorrect, the usual
pattern would be:
std::vector<int> grades;
while ( grades.size() != targetNumber ) {
int grade;
while ( !(std::cin >> grade) ) {
std::cout << "Integer wanted" << std::endl;
std::cin.clear();
std::cin.ignore( INT_MAX, '\n' );
}
grades.push_back( grade );
}
Still no for. (In fact, for loops with input are very, very
rare.)

Related

Add integers to array using cin simultaneously in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Hellow guys i want to add nine integers to array at once time without pressing enter key in run time. please guys tell me how to add nine integers to array simultaneously in C++.
Thanks!
If you want to process each integer value right after its input in console is complete (e.g. in that a blank indicates that the next integer value shall begin), you are in a bad position.
The reason is that terminal input (beyond of what your C++ program can influence) often is buffered, and even cin might not receive any character until Enter or EOF is pressed in the terminal.
There may exist workarounds like conio.h or ncurses, but the are not standard and probably not worth the effort in your situation unless you really need to implement integer scanning for a production environment tightly connected to console input.
Try it out and compare input taken directly from console to input from a stream that is already "filled" with enough input:
int main() {
stringstream ss("12 34 56 78 90 10 11 12 13");
//istream &in = ss; // would output each integer immediately.
istream &in = cin; // will probably wait for enter before processing begins.
int value = 0;
for (int i=0; i<9; i++) {
if (! (in >> value))
break;
cout << value << "; ";
}
}

Making a password type program that needs to accept letter and number combinations? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am making a shopping list program. For this program, I need to be able to type in a user input that accepts both number (1564, 121,1, etc) and word (hello, goodbye, etc) combinations. The program reads numbers just fine, but it cannot process words. Thank you in advance. The part of the code I am stuck with is below:
int code, option, count = 0;
double quantity, price, cost;
string description;
cin >> code;
while ((code != 123456789) && (count < 2))
{
cout << "Incorrect code, try again \n";
cin >> code;
count++;
if (count == 2)
{
cout << "max # of tries reached. Goodbye. \n";
system("pause");
}
}
Your code variable is now an int. If you wanted that to be a string, declare it so: std::string code;. Note that you might need to #include <string> in the very beginning. Also, if you want to compare it with numbers, either you call something like atoi() (string has .cstr()), or better yet, you might just compare it with "123456789". HTH.

Extracting integers from a ID string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to get the number 001 from the string UID001 (The user will always enter "UIDnnn"). I tried using cin.get and cin.ignore with delimiters but with no results. What is the most effective way to extract the integers from a string?
Well, the simplest c++ standard compliant solution seems to be as mentioned in my comment.
Read the ID value as a std:string:
std::string ID;
std::cin >> ID;
Get the substring with the number part:
std::string numpart = ID.substr(3);
Convert it to a numerical value:
int idnum = std::stoi(numpart);
This is one of those places that scanf and company really work well:
scanf("UID%d", &number);
With iostreams it's a bit uglier, but I'd consider something like:
for (int i=0; i<3; i++) {
char ch;
cin.get(ch);
}
cin >> number;

C++ Calculator With Unlimited Inputs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Hi I am a beginner to the c++ language and I would like to know if there is any way of writing a program with unlimited inputs. For example: I want to write a calculator program just to add numbers. That's easy enough but is there a way so that the user can add as many numbers as he wants without being asked how many numbers he wants. Such that if he wants to add three numbers he can just type "1+1+1" or if he wants to add four numbers he adds "+1" to the end of the previous line.Like this the user is not stuck to a fixed number of inputs or so he doesn't need to be asked how many inputs he wants. What functions in c++ do I need to know in order to do this
You can use a while loop to read from standard input. (std::cin) Some basic code to read from a while loop, and add the input to a sum is as follows:
#include <iostream>
#include <string>
#include <cstdlib>
int main(){
std::string line = "";
double sum = 0.0;
while(line != "end"){
std::cout<<"The current sum is: "<<sum<<std::endl;
std::cout<<"Enter the number you would like to add or \"end\" to exit: ";
std::cin>>line;
sum += atof(line.c_str());
}
std::cout<<"The final sum is: "<<sum<<std::endl;
}
This will read numbers until it receives the input "end".
For parsing and evaluating expressions that include infix operators, few things are simpler than the Shunting Yard Algorithm.
Implementing this in C++ is scarcely different than any other language with a container library (or built-in support) that provides stacks and queues. Here, you'll want to use std::stack and std::queue. The input to your program could be a single line (containing an expression typed by the user) read from std::cin (standard input, or the console) into an std::string.
This will not only permit expressions of any reasonable length, but also correctly handle arbitrary nesting of parenthesized sub-expressions, evaluation of special functions, and custom operators.
Yes. It is possible. You can use vector of ints. Get user's input and calculate sum of elements from vector. Put this in loop and that is what you wanted.
try this:
#include <iostream>
int main (int argc, char *argv[])
{
for (int i = 0; i < argc; i++)
std::cout << "argument " << i << " is " << argv[i] << std::endl;
return 0;
}

How to properly read from a .csv? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am having memory trouble with my code, and figured out that my code was being read wrong. For example the last value is adding numbers, not sure why. Also the names aren't coming out right.
This is what the output is looking like:
4101,BRAEBURN02.07682e-3172.07691e-317
4021,DELICIOUS02.07682e-3172.07691e-317
4020,DELICIOUS02.07682e-3172.07691e-317
4015,DELICIOUS02.07682e-3172.07691e-317
4016,DELICIOUS02.07682e-3172.07691e-317
4167,DELICIOUS02.07682e-3172.07691e-317
4124,EMPIRE,1,1.14,145.202.07682e-3172.07691e-317
4129,FUJI02.07682e-3172.07691e-317
4131,FUJI02.07682e-3172.07691e-317
As you can see the Empire was separated properly with the exception of the the last value.
Here's my code: the cout part was just for my personal use to see if the values were being inputted properly.
int main()
{
string name;
double price;
int by_weight;
double inventory;
int plu_code;
ifstream infile;
infile.open("inventory.csv");
while(!infile.eof())
{
stringstream ss;
string line = "";
getline(infile,line);
Tokenizer tok(line, ",");
ss << line;
ss >> plu_code >> name >> by_weight >> price >>inventory;
cout << plu_code<<"" <<name<<"" << by_weight<<"" << price <<""<<inventory<<"\n";
table[plu_code] = new Product(plu_code, name,by_weight, price,inventory);
numProducts++;
}
return 0;
}
The Empire line works because it's the only one whose name contains no whitespace. When you read strings from a stream, they are delimited by whitespace, so you only get the first word. If there are more words after that, then reading a double or other numeric type will fail because the stream is still pointing at non-numeric characters. You are not testing that your input operations succeeded, but it should have been obvious from your output.
I'm not sure what effect your Tokeniser class is supposed to have here. But perhaps have a look at this SO question for tokenising commas out of the stream. You can use a single getline call with a comma delimiter to read the name, and then normal << operator for the others.
[Edit] In fact, after cleaning up your question layout I notice that the Empire line doesn't work. It's reading the rest of the line as the name, and then still outputting uninitialised values. Which suggests to me your Tokeniser doesn't do anything at all.