如何从C中具有领先空格的stdin获取字符串输入? [英] How to get a string input from stdin that has leading white space in C?

查看:45
本文介绍了如何从C中具有领先空格的stdin获取字符串输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要一种使输入字符串以空格开头的解决方案吗?

Need a solution to get input string start with spaces?

我知道一种在输入中包含空格的方法

I know a method to include space in input

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

但是它仅适用于单词之间的间隔.我需要一个以空格开头的字符串的解决方案.而且我还需要变量中的起始空格

But its working only for space between words. I need a solution for string starts with spaces. And I also need the starting spaces in the variable

推荐答案

要获取用户输入的,请使用 fgets().

To get a line of user input, use fgets().

#define S_MAX_LENGTH
char s[S_MAX_LENGTH + 2];
if (fgets(s, sizeof s, stdin)) {
  s[strcspn(s, "\n")] = '\0'; // Should code want to lop off a potential trailing \n
  ....


请勿使用 scanf(%[^ \ n] s",s); gets(s); .它们遭受缓冲区溢出和其他问题的困扰.


Do not use scanf("%[^\n]s", s); nor gets(s);. They suffer from buffer overflow and other issues.

这篇关于如何从C中具有领先空格的stdin获取字符串输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆