#include <iostream> #include <vector> #include <cmath> #include <cstdlib> #include <stdio.h> #include <stdlib.h> using namespace std; void quickSort(int *numbers, int left, int right) // ф-ия сортировки Хоара в ней все в порядке. { int re; int l = left; int r = right; re = numbers[left]; while (left < right) { while ((numbers[right] >= re) && (left < right)) right--; if (left != right) { numbers[left] = numbers[right]; left++; } while ((numbers[left] <= re) && (left < right)) left++; if (left != right) { numbers[right] = numbers[left]; right--; } } numbers[left] = re; re = left; left = l; right = r; if (left < re) quickSort(numbers, left, re - 1); if (right > re) quickSort(numbers, re + 1, right); } int main() // В мейне предлагаю ввести сортируемый массив. Суть в том, что юзер вводит через консоль нужное ему кол-во элементов, нажимает пробел, и начинается сортировка. А мне нужно чтобы выдавало ошибку, как только юзер вводит символ или мусор по типу "1q2we" а не пропускало только 1. В этом и заключается моя проблема, не знаю как реализовать, очень долго мучаюсь. { int i=0, y=0, x=0, t=0; int b[100]; cin >> noskipws; cout<<"Vvedite ot 5 do 20 elementov" <<endl; while(cin >> x) { cin.ignore(10000, '\n'); i++; b[i]=x; y++; } quickSort(b, 0, y); for (int i = 0; i<y; i++) { cout<<b[i+1]<<" "; t++; } if ( t<5 ) cout<<"Error, vi vveli menee 5-i elementov" << endl; if ( t>20 ) cout<<"Error, vi vveli bolee 20-i elementov" << endl; system("pause"); return 0; } - Read the input as a string, then use x = stoi (s, p). Check p - if the entire input line is read - the input was an integer, otherwise it contained garbage. - Artemy Vysotsky
- Or here's another on stackoverflow.com/a/46087530/8491726 two variants of implementing input with validation - Artemy Vysotsky
|
2 answers
Use isdigit () to check.
- Please show more clearly. I tried to use this f-ju, but somehow it did not work with her - Markovad98
|
from bugs is not protected, but here is the solution. a bit harder than it should be. The bottom line is that you somehow all the input to drive into the string, and already the line to handle extra characters, the separation of spaces and so on. It was possible just to read everything through cin in the char array, including spaces, but it is easier to work with string IMHO. Try =)
#include <string> and
int main() { int t=0,i=0,y=0,j=0; char number[10]; //для хранения отдельного числа int b[100]; string c; cin >> noskipws; cout<<"Vvedite ot 5 do 20 elementov" <<endl; getline(cin,c,'\n'); while(i<c.length()){ if(!(isdigit(c[i]) || c[i]==' ' )) { //если символ не цифра, //возвращаем ошибку //та самая isdigit() cout<<"error: неверные символы"<<endl; return 1; } number[y]=c[i]; if(c[i]==' '||i==c.length()-1){ //если встретили пробел //или последнюю цифру b[j] = atoi(number); //преобразуем массив символов в //число y=0; //возвращаем индекс в начало массива number for (int s=0; s<10; s++) number[s] = 0; //обнуляем массив i++; j++; continue; } i++; y++; } quickSort(b, 0, j); for (int i = 0; i<j; i++){ cout<<b[i+1]<<" "; t++; } cout<<endl; if ( t<5 ) cout<<"Error, vi vveli menee 5-i elementov" << endl; if ( t>20 ) cout<<"Error, vi vveli bolee 20-i elementov" << endl; system("pause"); return 0; } |