2012-03-25 43 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