2012-03-25 42 views
2

我剛開始工作,發送文本超過淨(TON)我還沒有很啓動,但是當我編譯發生這種情況時,我在我的名字有一個空間爲什麼我的程序的行爲上Â小型程序奇怪

Username: Knight Hawk3 
LAN (1) or Net (0): 
(Here it wont let me enter data) 
Process returned 1 (0x1) execution time : 3.670 s 
Press any key to continue. 

以下是正常(應該)發生

Username: Knight 
LAN (1) or Net (0): 
1 

Process returned 1 (0x1) execution time : 2.134 s 
Press any key to continue. 

這裏是我的源

//////////////////////////////////////////////////////////// 
// Headers 
//////////////////////////////////////////////////////////// 
#include <SFML/Window.hpp> 
#include <SFML/System.hpp> 
#include <SFML/Graphics.hpp> 
#include <SFML/Network.hpp> 
#include <iostream> 
#include <string> 

using namespace std; 

bool firstrun = true; 

int main() { 

    if (firstrun) { 
     cout << "Username: "; 
     string name = ""; 
     cin >> name; 
     while (name == "") { 
      cout << "Invalid Enter a new name: "; 
      cin >> name; 
      cout << "\n"; 
     } 
    } 
    cout << "LAN (1) or Net (0): "; 
    int type; 
    cout << "\n"; 
    cin >> type; 
    while (type < 0) { 
      cout << "Invalid LAN (1) or Net (0): "; 
      cin >> type; 
    } 

    return true; 
} 

我跑WIN7,U sing代碼:: Blocks

爲什麼會發生這樣的空間?

回答

1

std::cin直到第一個空格讀取,但將其餘的保留在緩衝區中,這將用於以下的std::cin s。

如果你想讀的,直到第一'\n'(按回車鍵),你有

std::getline(std::cin, name); 
+0

由於更換std::cin,還有一件事我讓編譯器錯誤,當我使用getline函數的http:// pastebin.com/rHMhq4zR這裏是源代碼http://pastebin.com/df44MaBr – 2012-03-26 09:33:30

+0

@ KnightHawk3你也許已經替換了你讀取int的std :: cin。讀取包含空格的字符串時,只需要這樣做。有關'std :: getline'的更多信息,請參閱http://en.cppreference.com/w/cpp/string/basic_string/getline。 – inf 2012-03-26 09:40:17

+0

謝謝!我並沒有意識到getline()只是帶了字符串! – 2012-03-26 09:54:37