[英]Is there a formatter for scanf that allows me to ignore spaces until the next string, which I needs to read spaces? C language
Doing a poject for uni,为大学做一个项目,
Facing a problem where I need to read a line where I need to read the first char to choose the command (used a getchar, works fine).面临一个问题,我需要读取一行,我需要读取第一个字符来选择命令(使用 getchar,工作正常)。 The first char is separated by an undetermined amount of
' '
until a string is input.在输入字符串之前,第一个字符由不确定数量的
' '
分隔。 The string itself needs to be able to read until the end of the line (including ' '
).字符串本身需要能够读取到行尾(包括
' '
)。
Would this work?这行得通吗?
char c;
c= getchar();
while(c==' ')
c=getchar();
or would the last c
get "eaten"?还是最后一个
c
会被“吃掉”? then I would need to add it manually to the string, right?那么我需要手动将它添加到字符串中,对吗?
As a follow up, if I did after:作为后续行动,如果我之后做了:
string[0]=c;
scanf("%20[^\n]", string);
would I overwrite the first character?我会覆盖第一个字符吗?
Yes,是的,
string[0]=c;
scanf("%20[^\n]", string);
will overwrite the first character.将覆盖第一个字符。
You can add a whitespace character to the format specifier to tell scanf()
ignore whitespace characters.您可以向格式说明符添加一个空白字符,以告诉
scanf()
忽略空白字符。
scanf(" %20[^\n]", string);
If you want to skip whitespace characters manually, you can use ungetc()
to put the first wanted character back to the stream如果你想手动跳过空白字符,你可以使用
ungetc()
把第一个想要的字符放回 stream
ungetc(c, stdin);
scanf("%20[^\n]", string);
or manually put the character to the array, then have scanf()
store what is read after the first element.或者手动将字符放入数组,然后让
scanf()
存储在第一个元素之后读取的内容。
string[0]=c;
scanf("%20[^\n]", string + 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.