首先,我要说的是,发送一个硬编码的、完全格式化的字符串可以很好地工作。但是,当允许用户输入字符串时,代码会解析areaCode,但在交换解析过程中会失败。这是我的.h
// 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);
std::string getPhoneNumber() const;
void printPhoneNumber() const;
};
#endif下面是我的.cpp实现
// PhoneNumber.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cctype>
#include <stdexcept>
#include "PhoneNumber.h"
PhoneNumber::PhoneNumber(std::string number) {
setPhoneNumber(number);
}
void PhoneNumber::setPhoneNumber(std::string number) {
int length = number.length();
std::istringstream iss(number);
int count = 0;
while (!isdigit(number[count])) {
count += 1;
iss.ignore(1);
}
iss >> std::setw(3) >> areaCode;
count += 3;
while (!isdigit(number[count])) {
count += 1;
iss.ignore(1);
}
iss >> std::setw(3) >> exchange;
count += 3;
while (!isdigit(number[count])) {
count += 1;
iss.ignore(1);
}
if (length - count < 4) {
throw std::invalid_argument("Something wrong with your phone number input");
}
else {
iss >> std::setw(4) >> line;
}
}
void PhoneNumber::printPhoneNumber() const {
std::cout << "(" << areaCode << ") " << exchange << "-" << line;
}现在是我的简短测试代码。
// PhoneNumber testing
#include <iostream>
#include <string>
#include "PhoneNumber.h"
int main() {
std::string p1;
std::cout << "Enter phone number in format of (800) 555-1212: ";
std::cin >> p1;
PhoneNumber phone1(p1);
phone1.printPhoneNumber();
std::cout << std::endl;
}我已经尝试编写我的setPhoneNumber代码,以便它是用户容错的。所以第一个问题是我如何在用户输入的情况下工作?次要(无需应答)为什么它适用于硬编码的电话号码串,而不是用户输入?
发布于 2019-10-12 23:21:50
std::cin >> p1;将只读到第一个空格或回车符。因此,如果用户输入(800) 555-0123,您将只读取"(800)"。
你需要
std::getline(std::cin, p1);来读取输入。
它适用于硬编码字符串的原因是字符串赋值运算符不受此影响。在编写p1 = "(800) 555-0123";代码时,p1将设置为"(800) 555-0123"
https://stackoverflow.com/questions/58355577
复制相似问题