2013-11-28 114 views
1

我对C++还很陌生,刚开始学习类和OOP。我一直在尝试从任何我能想到的项目中选课,所以我开了一个电话课。代码如下。问题是无论我给它什么号码,它每次都显示相同的错误号码。疯狂的事情一开始我给电话类一个变量来存储它自己的号码,并给了类实例自己的号码。这个数字是它想要“呼叫”的数字。即使回头几次并确保我没有调用绞线变量,我完全删除了变量,代码仍然显示相同的数字。这个号码是214-748-3647。让我觉得我的电脑闹鬼了。谁能帮忙?即使在删除代码后,代码仍然显示变量

CODE并不能使电话呼叫的任何一种或任何连接什么那么

PHONE类的头

#ifndef PHONE_H_INCLUDED 
#define PHONE_H_INCLUDED 
#include <string> 

using namespace std; 

class Phone{ 
public: 

    string Brand; 
    int Serial; 
    string CellId; 

    void Call(); 

private: 

    void Dial(int NumberToDial); 

    void EndCall(); 

}; 


#endif // PHONE_H_INCLUDED 

电话源代码

#include <iostream> 
#include <string> 
#include <sstream> 
#include "phone.h" 

using namespace std; 

void Phone::Call(){ 

    string UserInput = "0"; 
    int NumberToCall = 0; 

    cout << "What number would you like to call?" << endl << endl; 

    getline(cin, UserInput); 

    if(UserInput.length() != 10){ 

     cout << endl << "invalid digits" << endl; 
     Call(); 

    } 
    else{ 

     stringstream(UserInput) >> NumberToCall; 
     Dial(NumberToCall); 

    } 
} 

void Phone::Dial(int NumberToDial = 0){ 

    ostringstream converter; 
    string Number; 

    converter << NumberToDial; 
    Number = converter.str(); 

    cout << "Dialing "; 

    for(int i=0;i<10;i++){ 

     cout << Number[i]; 

     if(i==2){ 

      cout << "-"; 
     } 

     if(i==5){ 

      cout << "-"; 

     } 

    } 

    cout << endl << endl << "Press any key to end the call..." << endl << endl; 


    cin.get(); 

    EndCall(); 


} 

void Phone::EndCall(){ 

    cout << "Call ended." << endl << endl; 

} 
A:

A aaaannnnd我的主要

#include <iostream> 
#include <cstdlib> 
#include "phone.h" 

using namespace std; 


int main() 
{ 

    Phone MyPhone; 

    MyPhone.Brand = "iPhone 5"; 
    MyPhone.CellId = "F2D9G3A2"; 
    MyPhone.Serial = 1411512; 

    MyPhone.Call(); 

    return 0; 
} 
+1

听起来像你还有旧版本的旧版本。确保在运行之前更改源代码实际上已重建它。 –

回答

1

这是一个非常简单的答案。你是代码和逻辑是好的。发生该错误是因为您将保存电话号码的std::string转换为整数。这是一个问题,因为典型的10位电话号码太大而不适合int类型。在这里看看你可以适应不同类型的最小和最大数字:http://www.cplusplus.com/reference/climits/

实际上看这条线。

类型长整型的目的最大值:2147483647(231-1)或更大

滑稽最大值如何是神秘的电话号码。

+0

哇!真是巧合!他以前的电话号码可能与长整数的最大值完全匹配..... – yizzlez

+1

实际上,如果他使用的是VS,那么如果在初始化时没有分配int值,它将自动分配给2147483647。我的猜测是stringstream由于溢出而失败,并且根本不改变int的值。 – IllusiveBrian

相关问题