如何从 C 中的 char 中获取 int
How to get int from char in C
(我是法国人,抱歉我的英语不好)
我不知道如何从 char[] 中获取 int,char 的模式每次都是相同的:"prendre 2"、"prendre 44"、"prendre 710"。 ..
我想检查句子的格式是否正确并得到整数
我已经尝试这样做,但如您所见,问题是我只能检查整数是否在 0-9 之间,因为我只检查一个字符。
[...]
else if (est_prendre(commande)){
/* if the output is 1*/
int number = commande[8]- '0'
}
int est_prendre(char *commande){
int i;
char temp[9] = "";
char c = commande[8];
int num = c - '0';
for (i=0; i<8; i++){
temp[i] = commande[i];
}
if (strcmp ("prendre ", temp) == 0)
{
if ( /* num IS INTEGER? */)
{
return 1;
}
else
{
return 0;
}
} else {
return 0;
}
}
我希望如果 commande = "prendre 3",est_prendre 的输出是 1,因为模式是正确的
然后将整数放入变量 number.
谢谢!
这是非常基础的,您应该(重新)阅读您用来学习该语言的任何关于 C 的 reference/tutorial。
您应该只使用 sscanf()
标准函数:
int value;
if (sscanf(commande, "prendre %d", &value) == 1)
{
... it was a match, the variable 'value' will be set to the number from the string
}
您可以删除将字符从 commande
复制到 temp
的(看起来很奇怪的)代码,当然还有 temp
变量。直接检查 commande
字符串即可。
假设 'commande + 8' 是一个有效的子字符串,你需要的是 atoi() 函数(ASCII 到整数)。这个函数有广泛的文档,你可以很容易地在网上找到它的用法。
int number = atoi(commande+8);
请记住,子字符串在第一个非数字字符处终止:
- atoi("23") returns 23
- atoi("51hh37") returns 51
- atoi("z3456") returns 0
注意:atoi将输入的字符串转换为整数,如果你确定它符合预期的输入,你可以使用它。因此,如果您希望在字符串中包含长整数或浮点值,您可以使用 atol()(ASCII 到长)或 atof()(ASCII 到浮点)。
(我是法国人,抱歉我的英语不好)
我不知道如何从 char[] 中获取 int,char 的模式每次都是相同的:"prendre 2"、"prendre 44"、"prendre 710"。 ..
我想检查句子的格式是否正确并得到整数
我已经尝试这样做,但如您所见,问题是我只能检查整数是否在 0-9 之间,因为我只检查一个字符。
[...]
else if (est_prendre(commande)){
/* if the output is 1*/
int number = commande[8]- '0'
}
int est_prendre(char *commande){
int i;
char temp[9] = "";
char c = commande[8];
int num = c - '0';
for (i=0; i<8; i++){
temp[i] = commande[i];
}
if (strcmp ("prendre ", temp) == 0)
{
if ( /* num IS INTEGER? */)
{
return 1;
}
else
{
return 0;
}
} else {
return 0;
}
}
我希望如果 commande = "prendre 3",est_prendre 的输出是 1,因为模式是正确的 然后将整数放入变量 number.
谢谢!
这是非常基础的,您应该(重新)阅读您用来学习该语言的任何关于 C 的 reference/tutorial。
您应该只使用 sscanf()
标准函数:
int value;
if (sscanf(commande, "prendre %d", &value) == 1)
{
... it was a match, the variable 'value' will be set to the number from the string
}
您可以删除将字符从 commande
复制到 temp
的(看起来很奇怪的)代码,当然还有 temp
变量。直接检查 commande
字符串即可。
假设 'commande + 8' 是一个有效的子字符串,你需要的是 atoi() 函数(ASCII 到整数)。这个函数有广泛的文档,你可以很容易地在网上找到它的用法。
int number = atoi(commande+8);
请记住,子字符串在第一个非数字字符处终止:
- atoi("23") returns 23
- atoi("51hh37") returns 51
- atoi("z3456") returns 0
注意:atoi将输入的字符串转换为整数,如果你确定它符合预期的输入,你可以使用它。因此,如果您希望在字符串中包含长整数或浮点值,您可以使用 atol()(ASCII 到长)或 atof()(ASCII 到浮点)。