[英]Get input separated by commas
I need to make a program that asks the user for input (until they terminate it by typing exit
). 我需要编写一个程序来询问用户输入(直到他们通过输入
exit
终止它)。 The input is separated by commas (example: value,value,value
). 输入以逗号分隔(例如:
value,value,value
)。 Each separate value then needs to be put into its own variable. 然后,每个单独的值都需要放入其自己的变量中。
Example: 例:
If the user types in hello,15,bye
, I need to put hello
into the first
variable, 15
into the second
variable, and bye
into the third
variable. 如果用户输入
hello,15,bye
,我需要将hello
放入第first
变量,将15
放入second
变量,并将bye
放入third
变量。
Here's what I have so far: 这是我到目前为止的内容:
int main(void) {
char input[100];
char first[100];
char second[100];
char third[100];
printf("Enter commands: ");
while(fgets(input, 100, stdin)) {
if(strncmp("exit", input, 4) == 0) {
exit(0);
}
// missing code
}
}
How would I separate the input by the commas and add the values into their own variables? 如何用逗号分隔输入并将值添加到它们自己的变量中?
Use sscanf()
and scan sets: 使用
sscanf()
和扫描集:
if (sscanf(input, "%99[^,],%99[^,],%99[^,\n]", first, second, third) != 3)
...oops...
The 99's appear because the strings are defined as 100, and this ensures no overflow, though with the input line also being 100, overflow isn't a problem. 出现99的原因是因为字符串定义为100,这可以确保没有溢出,尽管输入行也为100,但是溢出不是问题。
Two of the scan sets are %99[^,]
which looks like a limited form of regular expression; 其中两个扫描集是
%99[^,]
,看起来像是正则表达式的有限形式。 the caret means 'negated scan set', and therefore the string matches anything except a comma. 脱字号表示“否定扫描集”,因此该字符串与除逗号以外的其他任何内容匹配。 The last is
%99[^,\\n]
which excludes newlines as well as commas. 最后一个是
%99[^,\\n]
,其中不包括换行符和逗号。
You can skip leading white spaces on the names by adding spaces before the conversion specifications. 您可以通过在转换说明之前添加空格来跳过名称上的前导空白。 Trailing white spaces can't readily be avoided;
尾随空格很难避免。 if they're a problem, remove them after the conversion is successful.
如果有问题,请在转换成功后将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.