2011-11-16 64 views
2

我遇到了cin.peek()和cin.get()函數的問題。一般的輸入總是讓我無法迴避。基本上,我試圖能夠獲得一串數字(可以比int長,這就是爲什麼它使用字符)插入MyInt對象使用重載>>。我寫的MyInt類有一個名爲myNumber的動態char數組。 resize函數就是這樣做的,將動態數組的大小調整爲新的大小。get()和peek()幫助存儲大量數

我需要做兩件事情

  1. 忽略前導空格下一個字符不是0-9
  2. 停止。 (空格,字母)

以下是我有:

istream& operator>> (istream& s, MyInt& n) 
// Overload for the input operator                        
{ 
    char c;    // For peeking                       
    int x; 
    MyInt input;  // For storing                       
    unsigned int counter = 0; // counts # of stored digits                  

    while (isspace(s.peek())) 
    { 
    c = s.get(); 
    } 

    while (C2I(s.peek()) != -1) 
    { 
    x = C2I(s.get()); 
    input.myNumber[counter] = I2C(x); 
    counter++; 
    input.Resize(counter); 
    } 
    cout << "WHAH WHAH WEE WAH\n"; 

    n = input; 
} 

主要是調用只是這樣的:

cout << "Enter first number: "; 
cin >> x; 
cout << "Enter second number: "; 
cin >> y; 

cout << "You entered:\n"; 
cout << " x = " << x << '\n'; 
cout << " y = " << y << '\n'; 

這裏是一個輸出我:

Enter first number: 14445678954333 
WHAH WHAH WEE WAH 
Enter second number: 1123567888999H 
WHAH WHAH WEE WAH 
You entered: 
    x = 111111111111113 
    y = 11111111111119 

我是一名學生,這是'家庭作業'。就像所有的家庭作業一樣,我接受了我無法訪問的不合邏輯的東西。這一個是字符串類。這是工作中相當小的一部分,但它就像我身邊的一根刺。

回答

1

我會在調試器說運行它,並找出你搞亂了陣,我會猜測調整大小。由於您的輸入和輸出遵循一種模式,因此您可以使用這些模式。

14445678954333 
111111111111113 

1123567888999H 
11111111111119 

你是一個太長,第一個和最後一個號碼匹配。

1

爲什麼不總是使用std :: string來讀取和寫入你的數字?

然後,所有你需要的是從敏轉換 < - >的std :: string

class MyInt 
{ 
    vector<int> Integers; 
public: 
    MyInt(const string& source) 
    { 
     for (size_t i = 0; i < source.size(); ++i) 
     { 
      Integers.push_back(source[i] - '0'); 
     } 
    } 

    MyInt() 
    { 
    } 

}; 

istream& operator>> (istream& s, MyInt& n) 
{ 
    string input; 
    s >> input; 
    n = input; 
    return s; 
} 

int main() 
{ 

    MyInt input; 
    cout << "Enter first number: "; 
    cin >> input; 

    return 0; 
} 
+0

沒有提到它,但我沒有標記這個'家庭作業'。就像所有的家庭作業一樣,我接受了我無法訪問的不合邏輯的東西。這一個是字符串類。我將編輯主要。 – jordaninternets