Not effective validation algorithm for input format

1 Ansicht (letzte 30 Tage)
Destro Katramis
Destro Katramis am 1 Jun. 2020
Kommentiert: Ameer Hamza am 1 Jun. 2020
Hello everyone, I am asking as input, coordinates of quadrilateral vertices and I am adding an extra layer for format checking. Simply speaking inputs must be numerical.
vx=zeros(1,4);
vy=zeros(1,4);
vertices=['A'; 'B'; 'C'; 'D'];
fprintf('\nPlease enter the coordinates of vertices:\n');
for cnt=1:4
fprintf('\n For vertix <strong> %s </strong>', vertices(cnt));
fprintf(' :\n');
vx(cnt) = input(' Χ=');
vxtest=isnumeric(vx(cnt));
while vxtest==0
fprintf('ERROR: Non numerical character, try again.\n');
vx(cnt) = input(' Χ=');
vxtest=isnumeric(vx(cnt));
end
vy(cnt) = input(' Y=');
vytest=isnumeric(vy(cnt));
while vytest==0
fprintf('ERROR: Non numerical character, try again.\n');
vy(cnt) = input(' Y=');
vytest=isnumeric(vy(cnt));
end
end
vx=vx(1:4);
vy=vy(1:4);
But still it is possible to put a string as an input and continue to the next coordinate. At the end, there is an output area of a quadrilateral with vertices out of string coordinates.
Thanks in advance!

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 1 Jun. 2020
Try this
vx=zeros(1,4);
vy=zeros(1,4);
vertices=['A'; 'B'; 'C'; 'D'];
fprintf('\nPlease enter the coordinates of vertices:\n');
for cnt=1:4
fprintf('\n For vertix <strong> %s </strong>', vertices(cnt));
fprintf(' :\n');
temp = input(' Χ=');
vxtest=isnumeric(temp);
vx(cnt) = temp;
while vxtest==0
fprintf('ERROR: Non numerical character, try again.\n');
temp = input(' Χ=');
vxtest=isnumeric(temp);
vx(cnt) = temp;
end
temp = input(' Y=');
vytest=isnumeric(temp);
vy(cnt) = temp;
while vytest==0
fprintf('ERROR: Non numerical character, try again.\n');
temp = input(' Y=');
vytest=isnumeric(temp);
vy(cnt) = temp;
end
end
vx=vx(1:4);
vy=vy(1:4);
  2 Kommentare
Destro Katramis
Destro Katramis am 1 Jun. 2020
Bearbeitet: Destro Katramis am 1 Jun. 2020
I don't know what it was causing it but that fixed it! Thank you very much Ameer!!
Ameer Hamza
Ameer Hamza am 1 Jun. 2020
I am glad to be of help!
The problem was caused because vx is a numeric matrix (because of line vx=zeros(1,4)). So when you run the line
vx(cnt) = input(' Χ=');
the character is converted to a numeric value using ASCII table, and isnumeric() function return true.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by