[转]关于在C++中输入带空格的字符串的方法

这几天,在做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()输入是不会遇到空格就停止的函数。

源地址:http://blog.sina.com.cn/s/blog_5b37dc680100n92c.html

原文地址:https://www.cnblogs.com/cxeye/p/2472041.html