Using String-based Data Validation

Using String-based Data Validation

hat do a command shell, an online ordering system, and a report generator application have in common? Not much, really. Yet they all base their operation on an external source of data, be it a human user or a data file. By their nature, such applications must be prepared to detect invalid input and handle it in a reasonable manner.




The standard library offers only a limited input-validation mechanism. How can you ensure that users don’t accidentally enter a string as their zip code, for example? Although cin can detect such anomalous conditions, it has a cumbersome interface that doesn’t provide sufficient information about the cause of the error. Worse yet, cin doesn’t recover from errors automatically.



Instead of relying on cin to validate input, read the input as a string and then check it. If the string passes the test, convert it to the desired type, say int or double.

What Is Wrong with Datatype Analysis?
Suppose we want to develop a typical online flight booking system in which the user fills out the number of passengers, the requested date, the destination, the name etc. We need to determine the underlying types of each of the fields that the user should enter. For instance, the number of passengers is int whereas a passenger’s name is of type string:

class booking{private: int passengers; string name;//..};

We then read these fields as follows:

void booking::get_details(){ cout<< "enter number of passengers: "<< endl; cin>>passengers;//}

Alas, cin doesn’t block users from entering patently wrong data. If the user inserts the string “2w” as the number of passengers, cin will treat the letter ‘w’ as the beginning of the next field. Thus, not only do we end up with a dubious number of passengers, but the next field will contain a garbage value. As a partial solution, we can check the state of cin after each input operation by calling fail(). If cin is in an anomalous condition, fail() returns true. To see how it works, call get_details() again and insert the string “zz” as the number of passengers:

enter number of passengers: zz

As expected, a subsequent call to cin.fail() returns true. Yet we can’t tell what exactly is wrong with the input; all we know is that the user has entered an incorrect value (at this point, our passenger field contains a garbage value). To fix this, we can read the input in a loop, asking the users to re-enter this datum if fail() is true. This, however, isn’t an ideal solution for several reasons. To begin with, we don’t know what exactly is wrong with the input, so we can’t give the users a detailed error message. Furthermore, cin doesn’t clear the error automatically; you’d have to call clear() to clear the error. Obviously, we need a better validation method.

String-based Data Validation Works Better
Instead of relying on a field’s datatype, read all the values as strings and test them. A valid number of passengers, for example, should only contain digits. The revised get_details() function now looks as follows:

#include void booking::get_details(){ string num; bool kosher=false; cout<< "enter number of passengers: "<> endl; cin>>num;  //make sure that num contains digits exclusively if(find_if(num.begin(),num.end(), nondigit())==num.end())  kosher=true; // we have a valid string else  // we have an invalid string}

The interesting part is the find_if() call. The algorithm find_if() defined in takes three parameters: two input iterators that mark the sequence’s beginning and end, respectively and a predicate. Our predicate can be an address of a function, say isalpha() or it can be a function object whose overloaded () operator returns bool. For each character in the string num, find_if() calls the predicate. If any of the characters isn’t a digit, find_if() returns an iterator pointing to the first non-digit character. Otherwise, it returns a value equal to the second argument. In other words, the user’s input is kosher if find_if() returns num.end().

The nondigit function object uses the standard function isdigit() declared in . It negates the result of isdigit() and returns it:

class nondigit{public: bool operator() (char c) {return !isdigit(c);}};

If the string is kosher, we can proceed to the next step, namely converting it to int. We use a stringstream object for this:

if(kosher==true){stringstream s(num); //insert string to ss>>passenger; //extract int value and write it to passenger}

In case of an invalid string, we can display a detailed error message to the user, possibly highlighting the first invalid characters in the entered string.

devx-admin

devx-admin

Share the Post:
Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private,

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications,

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

AI Tool

Unleashing AI Power with Microsoft 365 Copilot

Microsoft has recently unveiled the initial list of Australian clients who will benefit from Microsoft 365 (M365) Copilot through the exclusive invitation-only global Early Access Program. Prominent organizations participating in

Microsoft Egnyte Collaboration

Microsoft and Egnyte Collaboration

Microsoft has revealed a collaboration with Egnyte, a prominent platform for content cooperation and governance, with the goal of improving real-time collaboration features within Microsoft 365 and Microsoft Teams. This

Best Laptops

Top Programming Laptops of 2023

In 2023, many developers prioritize finding the best laptop for programming, whether at home, in the workplace, or on the go. A high-performing, portable, and user-friendly laptop could significantly influence

Renaissance Gaming Magic

AI Unleashes A Gaming Renaissance

In recent times, artificial intelligence has achieved remarkable progress, with resources like ChatGPT becoming more sophisticated and readily available. Pietro Schirano, the design lead at Brex, has explored the capabilities

New Apple Watch

The New Apple Watch Ultra 2 is Awesome

Apple is making waves in the smartwatch market with the introduction of the highly anticipated Apple Watch Ultra 2. This revolutionary device promises exceptional performance, robust design, and a myriad

Truth Unveiling

Unveiling Truths in Bowen’s SMR Controversy

Tony Wood from the Grattan Institute has voiced his concerns over Climate and Energy Minister Chris Bowen’s critique of the Coalition’s support for small modular nuclear reactors (SMRs). Wood points

Avoiding Crisis

Racing to Defy Looming Financial Crisis

Chinese property developer Country Garden is facing a liquidity challenge as it approaches a deadline to pay $15 million in interest associated with an offshore bond. With a 30-day grace

Open-Source Development

Open-Source Software Development is King

The increasingly digital world has led to the emergence of open-source software as a critical factor in modern software development, with more than 70% of the infrastructure, products, and services

Home Savings

Sensational Savings on Smart Home Security

For a limited time only, Amazon is offering massive discounts on a variety of intelligent home devices, including products from its Ring security range. Running until October 2 or while

Apple Unleashed

A Deep Dive into the iPhone 15 Pro Max

Apple recently unveiled its groundbreaking iPhone 15 Pro and iPhone 15 Pro Max models, featuring a revolutionary design, extraordinary display technology, and unrivaled performance. These new models are the first

Renewable Crypto Miners

Crypto Miners Embrace Renewable Energy?

As the cryptocurrency sector deals with the fallout from the FTX and Celsius exchange collapses, Bitcoin miners are increasingly exploring alternative energy sources to reduce expenses and maintain profitability. Specialists

Laptop Savings

The HP Omen 16 is a Gamer’s Dream

Best Buy is currently offering an unbeatable deal on the HP Omen 16 gaming laptop, giving potential buyers the chance to save a significant $720 on their purchase. Originally priced

How to Check for Vulnerabilities in Exchange Server

It is imperative to keep your systems and infrastructure up-to-date to mitigate security issues and loopholes, and to protect them against any known vulnerabilities and security risks. There are many

Data Center Creation

Transforming Corporate Campuses into Thriving Data Centers

Dallas-based developer Compass Datacenters has purchased a 197-acre ex-corporate campus in Hoffman Estates, Illinois for an estimated $194 million. This acquisition occurs as more companies are downsizing and consolidating their