這幾天,在做assignment的時候發現了一個問題,當我在cin>>中輸入帶有空格的課程名字的時候,程序會中斷。我也在網上查看了很多關於這個問題的資料,例如一下的代碼:
#include <iostream.h>
void main()
{
char str[20];
cout<<"Input :";
cin.getline(str,20);
cout<<str<<endl;
}
這個代碼我親自用過,但是在我的電腦以及VMware虛擬機中的VC 6.0中測試的時候,發現根本不行,依然中斷。而在學校的機房卻完全可以,有人說是我的人品問題。
后來找到了一個方法:
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
void main()
{
char unitName[30];
cout<<"\nPlease enter the unit name:\n";
getchar();
gets(unitName);
cout<<unitName<<endl;
}
用getchar(); 和gets(unitName);的組合,
getchar()是程序等着用戶按鍵,用戶輸入的字符被存放在鍵盤緩沖區中,直到用戶按回車為止(回車字符也放在緩沖區中)。
而gets()輸入是不會遇到空格就停止的函數。