How to restrict input into numbers only c++ - visual-c++

Is there a way to prevent the program from executing characters in "Menu" type program where you choose options while running console and enter numbers only to do steps and browse data.
My program is a book catalog where you can review, change, add or delete information.
Things wouldn't be as bad but the the thing is, that when you enter a letter or non-number character the program gets messy and stuck.
I am not adding my code since I think that there should be a universal command to get rid of my problem + it would take some time to translate my code into EN.

The easiest way to do it is use the getline function I think. Instead of using cin >> num; for example, you would use getline(cin,value); where "value" is a string that you first store your input in. Then you can do num = atoi(value.c_str()); to save the string input as an integer value into "num". If "num" is a float, then just use atof instead of atoi. This way if the string is not a number, it just sets the value to 0. You could then use an if statement to display an error message if the value of num == 0. Hope that helps. Good luck!

If your application runs in a console and you are worried about wrong (non-number) input, perhaps you should the input not as a number, but as a text and then parse it to see it is really a number. If not, tell the user the input is incorrect and let them enter it again.

Related

Way to find a number at the end of a string in Smalltalk

I have different commands my program is reading in (i.e., print, count, min, max, etc.). These words can also include a number at the end of them (i.e., print3, count1, min2, max6, etc.). I'm trying to figure out a way to extract the command and the number so that I can use both in my code.
I'm struggling to figure out a way to find the last element in the string in order to extract it, in Smalltalk.
You didn't told which incarnation of Smalltalk you use, so I will explain what I would do in Pharo, that is the one I'm familiar with.
As someone that is playing with Pharo a few months at most, I can tell you the sheer amount of classes and methods available can feel overpowering at first, but the environment actually makes easy to find things. For example, when you know the exact input and output you want, but doesn't know if a method already exists somewhere, or its name, the Finder actually allow you to search by giving a example. You can open it in the world menu, as shown bellow:
By default it seeks selectors (method names) matching your input terms:
But this default is not what we need right now, so you must change the option in the upper right box to "Examples", and type in the search field a example of the input, followed by the output you want, both separated by a ".". The input example I used was the string 'max6', followed by the desired result, the number 6. Pharo then gives me a list of methods that match that:
To get what would return us the text part, you can make a new search, changing the example output from number 6 to the string 'max':
Fortunately there is several built-in methods matching the description of your problem.
There are more elegant ways, I suppose, but you can make use of the fact that String>>#asNumber only parses the part it can recognize. So you can do
'print31' reversed asNumber asString reversed asNumber
to give you 31. That only works if there actually is a number at the end.
This is one of those cases where we can presume the input data has a specific form, ie, the only numbers appear at the end of the string, and you want all those numbers. In that case it's not too hard to do, really, just:
numText := 'Kalahari78' select: [ :each | each isDigit ].
num := numText asInteger. "78"
To get the rest of the string without the digits, you can just use this:
'Kalahari78' withoutTrailingDigits. "Kalahari"6
As some of the Pharo "OGs" pointed out, you can take a look at the String class (just type CMD-Return, type in String, hit Return) and you will find an amazing number of methods for all kinds of things. Usually you can get some ideas from those. But then there are times when you really just need an answer!

need guidance with basic function creation in MATLAB

I have to write a MATLAB function with the following description:
function counts = letterStatistics(filename, allowedChar, N)
This function is supposed to open a text file specified by filename and read its entire contents. The contents will be parsed such that any character that isn’t in allowedChar is removed. Finally it will return a count of all N-symbol combinations in the parsed text. This function should be stored in a file name “letterStatistics.m” and I made a list of some commands and things of how the function should be organized according to my professors' lecture notes:
Begin the function by setting the default value of N to 1 in case:
a. The user specifies a 0 or negative value of N.
b. The user doesn’t pass the argument N into the function, i.e., counts = letterStatistics(filename, allowedChar)
Using the fopen function, open the file filename for reading in text mode.
Using the function fscanf, read in all the contents of the opened file into a string variable.
I know there exists a MATLAB function to turn all letters in a string to lower case. Since my analysis will disregard case, I have to use this function on the string of text.
Parse this string variable as follows (use logical indexing or regular expressions – do not use for loops):
a. We want to remove all newline characters without this occurring:
e.g.
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
In my younger and more vulnerableyears my father gave me some advicethat I’ve been turning over in my mindever since.
Replace all newline characters (special character \n) with a single space: ' '.
b. We will treat hyphenated words as two separate words, hence do the same for hyphens '-'.
c. Remove any character that is not in allowedChar. Hint: use regexprep with an empty string '' as an argument for replace.
d. Any sequence of two or more blank spaces should be replaced by a single blank space.
Use the provided permsRep function, to create a matrix of all possible N-symbol combinations of the symbols in allowedChar.
Using the strfind function, count all the N-symbol combinations in the parsed text into an array counts. Do not loop through each character in your parsed text as you would in a C program.
Close the opened file using fclose.
HERE IS MY QUESTION: so as you can see i have made this list of what the function is, what it should do, and using which commands (fclose etc.). the trouble is that I'm aware that closing the file involves use of 'fclose' but other than that I'm not sure how to execute #8. Same goes for the whole function creation. I have a vague idea of how to create a function using what commands but I'm unable to produce the actual code.. how should I begin? Any guidance/hints would seriously be appreciated because I'm having programmers' block and am unable to start!
I think that you are new to matlab, so the documentation may be complicated. The root of the problem is the basic understanding of file I/O (input/output) I guess. So the thing is that when you open the file using fopen, matlab returns a pointer to that file, which is generally called a file ID. When you call fclose you want matlab to understand that you want to close that file. So what you have to do is to use fclose with the correct file ID.
fid = open('test.txt');
fprintf(fid,'This is a test.\n');
fclose(fid);
fid = 0; % Optional, this will make it clear that the file is not open,
% but it is not necessary since matlab will send a not open message anyway
Regarding the function creation the syntax is something like this:
function out = myFcn(x,y)
z = x*y;
fprintf('z=%.0f\n',z); % Print value of z in the command window
out = z>0;
This is a function that checks if two numbers are positive and returns true they are. If not it returns false. This may not be the best way to do this test, but it works as example I guess.
Please comment if this is not what you want to know.

automating string and number concatenation

I'm having some trouble automating a matlab script which should prompt the user for the variable they are interested in, as well as the date range they want. I then want the script to concatenate their answers within a naming convention for the file they will ultimately load.
variable=input('please input variable of interest');
% temp
start=input('please state the start date in the form yymmdd: ');
%130418
enddate=input('please state the end date in the form yymmdd: ');
%140418
file=sprintf('%s_dailydata_%d_%d.csv',variable,start,enddate);
%so I thought 'file' would look like: temp_dailydata_130418_140418.csv
vardata=load(file);
the two numbers representing the dates are not causing any issues, but the fact that 'variable' is a string is. I know if I put apostrophes before and after 'temp' when I'm promted, it will work, but I have to assume that the end user won't know to do this. I tried putting curly braces around 'please input your variable..', but that didn't help either. Obviously this approach assumes that the date being requested exists in a filename.
Can anyone offer any advice? Perhaps the sprintf function is not the best option here?
Don't use 'end' as a variable name, it is a reserved name and using it could create conflicts with any function or logic block you're defining.
If you know your input is going to be a string: from the documentation for input()
str = input(prompt,'s')
Returns the entered text as a MATLAB string, without evaluating expressions.
As for knowing whether or not the file exists, that's something you'd have to incorporate some error logic for. Either a try/catch block with your load() call or you could use uigetfile() to get the filename.

Quick variable question

I have an EditText object (et_travel) on my screen that's asking for miles traveled. I grab that data like this:
float travel = Float.parseFloat(et_travel.getText().toString());
if(travel > 40000){
I just discover that if someone puts 40000 in the EditText, everything works fine, but if they put 40,000 (adding a comma to the number), I force close on the float travel = ...statement.
How can I evaluate the number without having a problem from the user adding a comma?
Is this in Java? It appears to be, but I'm wondering if I'm mistaken. Regardless, I would suggest you remove all of the characters from the string that are not of a numeric type. A way to do this may be using a regular expression.
A way to do this in Java may be the following:
String input = et_travel.getText().toString();
input = input.replaceAll("[^0-9]", "");
float travel = Float.parseFloat(input);
...
This way, you strip anything that is a non-numeric value from the string first, and then attempt to do your work. Obviously do some error checking before this (like input is not null and such). One change that is needed however is that you may need to maintain the '.' character (if you're given non-integer values). This would require changing the first regex a bit.
Check here: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
What you need is some validation on the input. Before converting the string into a float parse the string. If there are any ','s then remove them. If there is just junk then reject the input, otherwise someone could put a word or anything else in the input and cause havoc in your program.
Check out
inputType to restrict user input
android:inputType="number"

Protection from Format String Vulnerability

What exactly is a "Format String Vulnerability" in a Windows System, how does it work, and how can I protect against it?
A format string attack, at its simplest, is this:
char buffer[128];
gets(buffer);
printf(buffer);
There's a buffer overflow vulnerability in there as well, but the point is this: you're passing untrusted data (from the user) to printf (or one of its cousins) that uses that argument as a format string.
That is: if the user types in "%s", you've got an information-disclosure vulnerability, because printf will treat the user input as a format string, and will attempt to print the next thing on the stack as a string. It's as if your code said printf("%s");. Since you didn't pass any other arguments to printf, it'll display something arbitrary.
If the user types in "%n", you've got a potential elevation of privilege attack (at least a denial of service attack), because the %n format string causes printf to write the number of characters printed so far to the next location on the stack. Since you didn't give it a place to put this value, it'll write to somewhere arbitrary.
This is all bad, and is one reason why you should be extremely careful when using printf and cousins.
What you should do is this:
printf("%s", buffer);
This means that the user's input is never treated as a format string, so you're safe from that particular attack vector.
In Visual C++, you can use the __Format_string annotation to tell it to validate the arguments to printf. %n is disallowed by default. In GCC, you can use __attribute__(__printf__) for the same thing.
In this pseudo code the user enters some characters to be printed, like "hello"
string s=getUserInput();
write(s)
That works as intended. But since the write can format strings, for example
int i=getUnits();
write("%02d units",i);
outputs: "03 units". What about if the user in the first place wrote "%02d"... since there is no parameters on the stack, something else will be fetched. What that is, and if that is a problem or not depends on the program.
An easy fix is to tell the program to output a string:
write("%s",s);
or use another method that don't try to format the string:
output(s);
a link to wikipedia with more info.

Resources