2015-09-25 30 views
0

這是我的頭文件的一部分。Overloading >>使用字符串類

#ifndef MY_STRING_H 
#define MY_STRING_H 

#include <iostream> 


using namespace std; 

class MyString 
{ 
public: 

MyString(); 
MyString(const char[]); 
MyString(const MyString&); 
~MyString(); 

private: 
char *  pChar; 
size_t  NumChars; 
size_t  NumSlots; 

friend istream &operator >>(istream &, MyString &); 
}; 

inline istream& operator >>(istream &in, MyString & Str) 
{ 
in >> Str.pChar; 
in >> Str.NumChars; 
in >> Str.NumSlots; 
return in; 
} 

在我的main.cpp我嘗試

cout << "Enter a string: "; 
cin >> Str6; 

我遇到的這些問題,我似乎無法想出一個辦法,爲正在進入新的字符串分配足夠的空間而且它似乎也只是把角色帶到第一個空間。所以輸出是這樣的:

Enter a String: does it work? 
Your String is: does 

然後我得到一個寫入內存後,堆緩衝區錯誤彈出結束。 我在想我可以使用我的拷貝構造函數中的一些代碼臨時構建一個具有足夠空間的Str obj,但我不知道如何獲得足夠大的字符數。我在正確的軌道上嗎?

+2

cin返回空格分隔的數據。您可能需要getline() –

+1

您不應該讀入'pChar' - 它是一個字符指針,可能指向一個現有緩衝區,對於傳入的文本來說太小(或者如果初始化或清除它,則根本沒有緩衝區到'nullptr')。你還需要闡明你的設計:你的實現在>> Str.pChar >> Str.NumChars >> Str.NumSlots;'暗示用戶希望在輸入字符串時輸入三樣東西,但是你輸入一個字符串:它的工作原理?'示例顯示,這不是你想要它如何工作。無論是先輸入'NumChars',這樣你就可以相應地分配,或者讀取char-by-char增長緩衝區。 –

回答

2

解決該問題的一種方法是更改​​輸入的順序。在將數據讀入pChar之前,請閱讀NumChars

inline istream& operator >>(istream &in, MyString & Str) 
{ 
    // Expect the input to be <NumChars> <the characters> <NumSlots> 
    // or 
    // Expect the input to be <NumChars> <NumSlots> <the characters> 

    // Assumuing the first format... 

    // Read the number of characters. 
    in >> Str.NumChars; 

    // Allocate memory for the characters 
    Str.pChar = new [Str.NumChars+1]; 

    // Skip one character, the separator between <NumChars> and <the characters> 
    in.ignore(1); 

    // Read the characters. 
    for (int i = 0; i < Str.NumChars; ++i) 
    { 
     Str.pChar[i] = in.get(); 
    } 
    Str.pChar[Str.NumChars] = '\0'; 

    // Now read NumSlots. 
    in >> Str.NumSlots; 

    return in; 
} 

我完全省去了錯誤檢查代碼。在生產程序中,在修改對象之前,必須確保所有輸入操作都成功。

+0

你不需要'ignore(1)'。當到達空格時,'>>'停止讀取,或者與正在讀取的數據類型不匹配的字符。下一個'>>'將在讀取下一個值之前跳過任何前導空格。所以,考慮到如果用戶輸入'5hello'(它在首次讀取整數時有效)而不是'5 hello',那麼'ignore(1)'會破壞數據。另外,你不需要'in.get()'循環,你可以使用'in.read(Str.pChar,Str.NumChars)'代替。 –

+0

@RemyLebeau,如果沒有'ignore(1)',那麼無論我們使用'in.get()'還是'in.read()',下一個空格都會被讀入'pChar'。 –

+0

如果您需要手動跳過空格,請使用in >> std :: ws而不是'in.ignore()'。 –

相關問題