首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用istringstream和istringstream.ignore解析电话号码时出现C++问题

使用istringstream和istringstream.ignore解析电话号码时出现C++问题
EN

Stack Overflow用户
提问于 2019-10-12 23:17:43
回答 1查看 69关注 0票数 0

首先,我要说的是,发送一个硬编码的、完全格式化的字符串可以很好地工作。但是,当允许用户输入字符串时,代码会解析areaCode,但在交换解析过程中会失败。这是我的.h

代码语言:javascript
复制
// 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实现

代码语言:javascript
复制
// 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;
}

现在是我的简短测试代码。

代码语言:javascript
复制
// 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代码,以便它是用户容错的。所以第一个问题是我如何在用户输入的情况下工作?次要(无需应答)为什么它适用于硬编码的电话号码串,而不是用户输入?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-12 23:21:50

代码语言:javascript
复制
std::cin >> p1;

将只读到第一个空格或回车符。因此,如果用户输入(800) 555-0123,您将只读取"(800)"

你需要

代码语言:javascript
复制
std::getline(std::cin, p1);

来读取输入。

它适用于硬编码字符串的原因是字符串赋值运算符不受此影响。在编写p1 = "(800) 555-0123";代码时,p1将设置为"(800) 555-0123"

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58355577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档