在 C 中存储字符串中的两个整数
我正在尝试编写一个从字符串中打印两个数字的程序。
例如, string = '20,66' 我试图将这个字符串分开,以便我可以将 '20' 和 '66' 存储到两个单独的变量中。
这是我正在处理的代码:
#include <stdio.h>
char line[80];
int main(void)
{
// Variables
int start_number, end_number;
int i, j;
while(1)
{
printf("Enter a number: ");
fgets( line, sizeof(line), stdin);
// How to find Comma
for( i=0; i < strlen(line); i++)
{
if(line[i]==',') break;
}
// How to find two numbers
for(j = 0; j < i; j++)
{
printf("1: %c\n", line[j]);
}
for(j = i + 1; j < strlen(line); j++)
{
printf("2: %c\n", line[j]);
}
if (strcmp(line, "quit\n") == 0)
{
printf("Now terminating program...");
break;
}
}
}
到目前为止,我只能存储单位数字变量,并且由于某种原因打印额外的行。
任何建议或意见将不胜感激。
I am trying to write a program that prints two numbers from a string.
For example, string = '20,66' I am trying to break this string apart so I can store '20' and '66' into two separate variables.
Here is the code I am working on:
#include <stdio.h>
char line[80];
int main(void)
{
// Variables
int start_number, end_number;
int i, j;
while(1)
{
printf("Enter a number: ");
fgets( line, sizeof(line), stdin);
// How to find Comma
for( i=0; i < strlen(line); i++)
{
if(line[i]==',') break;
}
// How to find two numbers
for(j = 0; j < i; j++)
{
printf("1: %c\n", line[j]);
}
for(j = i + 1; j < strlen(line); j++)
{
printf("2: %c\n", line[j]);
}
if (strcmp(line, "quit\n") == 0)
{
printf("Now terminating program...");
break;
}
}
}
So far, I am only able to store single digit variables and for some reason prints an extra line.
Any suggestions or advice will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
很简单:
Quite simple:
查看 scanf 及其相关内容:
可能会引入安全漏洞,因此请务必阅读并理解安全性部分,以便您有足够的存储空间来存储要扫描的值。
Look into scanf and its relatives:
It's possible to introduce security vulnerabilities so be sure to read and understand the section on security so that you have enough storage for the values you're trying to scan.
多种方法之一:找到逗号后,可以将逗号更改为
(char)0
。然后你将有两个字符串,一个是line
,另一个是line+comma_offset+1
。两者都只是数字,可以传递给atoi。这个技巧之所以有效,是因为 C 字符串的实现方式——字符串的末尾是 0。因此,您采用一个字符串:
并将逗号替换为 null:,
那么您就有了两个 C 字符串。这就是
strtok
和strtok_r
的工作原理。One of many approaches: Once you find the comma, you can change the comma to
(char)0
. Then you will have two strings, one will beline
the other one will be atline+comma_offset+1
. Both are just the numbers and can be passed toatoi
.This trick works due to the way C strings are implemented—the end of the string is a 0. So, you take a string:
and replace the comma with a null:
then you have two C strings. This is how
strtok
andstrtok_r
work.也许您不希望在 for 循环中打印“1:”和/或换行符(“\n”)。将此:更改
为:
Perhaps you dont want to have "1: " and/or a NEWLINE ("\n") printed within the for loop. Change this:
to this: