首页 > 技术文章 > 输入带空格字符串的两种方法

cangT-Tlan 2017-09-11 08:39 原文

这是我们平常用的:

  char s[100];

  scanf("%s",s);//cin>>s;

  输入字符串时,当遇到空格就自动停止输入,导致空格后门的字符没有按我们设想的输入。

 

  现在有两种方法可以输入带空格的字符串:

  第一,用get()函数:

  char str[100];

  get(str);

  注:get()函数在linux使用会有这条错误。在linux(fedora10)下的话建议使用第二种方法。

  test.o: In function `main':
  test.c:(.text+0x1df): warning: the `gets' function is dangerous and should not be used.

 

  第二,用scanf函数:

  char str[100];

  scanf("%[^\n]",str);

  注:\n代表回车,^代表取反,整体的意思是只有输入回车键时才会结束输入。

推荐阅读