【问题标题】:C++ - How am I misusing ignore with istringstream?C++ - 我如何在 istringstream 中误用忽略?
【发布时间】:2019-10-12 04:54:11
【问题描述】:

我计划在主代码中要求用户以 (800) 555-1212 的形式输入电话号码,然后将其发送到我的 PhoneNumber 构造函数,然后发送到 setPhoneNumber 进行分解,设置我的私有变量,并分析错误。此外,我想编写我的 setPhoneNumber 代码,以便解决原始输入中的用户错误。我的 PhoneNumber.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);
      void printPhoneNumber() const;
};
#endif

这是我的 PhoneNumber.cpp 代码

// 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;
            }
         }
      }
   }
}

我得到的错误与 std::ignore 一致,但我不知道我是如何错误地使用它的。 g++ 编译器的错误是:

PhoneNumber.cpp:23:32:错误:不匹配调用‘(const std::_Swallow_assign) ()’

iss >> std::ignore();

【问题讨论】:

    标签: c++ istringstream


    【解决方案1】:

    std::ignore() 的目的与您希望实现的目的截然不同。而不是

    iss >> std::ignore();
    

    使用

    iss.ignore();
    

    您可以在https://en.cppreference.com/w/cpp/io/basic_istream/ignore 上查看std::istream::ignore() 的文档和示例用法。

    【讨论】:

      【解决方案2】:

      std::ignore 并没有像你想象的那样做:它用于元组。

      相反,您要查找的内容实际上称为std::istream::ignore()。你可以这样使用它:

      iss.ignore();
      

      更多关于std::istream::ignore()的信息,可以阅读this question.

      【讨论】:

        猜你喜欢
        • 2016-09-27
        • 1970-01-01
        • 2017-08-23
        • 2019-04-28
        • 1970-01-01
        • 2020-06-14
        • 2013-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多