I plan in main code to ask user to input phone number in form of (800) 555-1212, which will be sent to my PhoneNumber constructor then sent to setPhoneNumber for breaking it up, setting my private variables, and analysis for errors. Additionally, I wanted to write my setPhoneNumber code so it accounts for user errors in the original input. My PhoneNumber.h code is:
// PhoneNumber.h
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include <string>
class PhoneNumber {
private:
short areaCode;
short exchange;
short line;
public:
PhoneNumber(std::string number);
void setPhoneNumber(std::string number);
void printPhoneNumber() const;
};
#endif
And here is my PhoneNumber.cpp code
// PhoneNumber.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cctype>
#include "PhoneNumber.h"
PhoneNumber::PhoneNumber(std::string number) {
setPhoneNumber(number);
}
void PhoneNumber::setPhoneNumber(std::string number) {
bool areaCodeDone = false;
bool exchangeDone = false;
int length = number.length();
std::istringstream iss(number);
for (int i = 0; i < length; i++) {
if (! areaCodeDone) {
if (! std::isdigit(number[i])) {
std::string str;
iss >> std::ignore();
}
else {
iss >> std::setw(3) >> areaCode;
areaCodeDone = true;
}
}
else if (! exchangeDone) {
if (! std::isdigit(number[i])) {
iss >> std::ignore();
}
else {
iss >> std::setw(3) >> exchange;
exchangeDone = true;
}
}
else {
if (! std::isdigit(number[i])) {
iss >> std::ignore();
}
else {
if (length - i < 4) {
throw std::invalid_argument("Something wrong with phone number entry.");
}
else {
iss >> std::setw(4) >> line;
}
}
}
}
}
The errors I get are on my lines with std::ignore, but I don't know how I am using it incorrectly. Error from g++ compiler is:
PhoneNumber.cpp:23:32: error: no match for call to ‘(const std::_Swallow_assign) ()’
iss >> std::ignore();
std::ignore()
has a very different purpose than what you are hoping to accomplish. Instead of
iss >> std::ignore();
use
iss.ignore();
You can see the documentation of std::istream::ignore()
and example usage at https://en.cppreference.com/w/cpp/io/basic_istream/ignore.