我已经尝试过将这段代码将Str []字符串分成2个字符串,但是我的问题是“我想将John(name)作为字符串,将100(marks)作为整数”,我该怎么办,有什么建议吗?
#include <stdio.h>
#include <string.h>
void main()
{
char Str[] = "John,100";
int i, j, xchange;
char name[50];
char marks[10];
j = 0; xchange = 0;
for(i=0; Str[i]!='\0'; i++){
if(Str[i]!=',' && xchange!=-1){
name[i] = Str[i];
}else{
xchange = -1;
}
if(xchange==-1){
marks[j++] = Str[i+1];
}
}
printf("Student name is %s\n", name);
printf("Student marks is %s", marks);
}
最佳答案
如何将“ John,100”分成2个字符串?
共有三种常见方法:
使用strtok()
将字符串拆分为单独的标记。这将修改原始字符串,但是实现起来非常简单:
int main(void)
{
char line[] = "John,100;passed";
char *name, *score, *status;
/* Detach the initial part of the line,
up to the first comma, and set name
to point to that part. */
name = strtok(line, ",");
/* Detach the next part of the line,
up to the next comma or semicolon,
setting score to point to that part. */
score = strtok(NULL, ",;");
/* Detach the final part of the line,
setting status to point to it. */
status = strtok(NULL, "");
请注意,如果更改
char line[] = "John,100";
,则status
将为NULL
,但是可以安全地运行该代码。因此,实际上,如果您要求所有三个字段都在
line
中存在,那么确保最后一个字段不是NULL
就足够了: if (!status) {
fprintf(stderr, "line[] did not have three fields!\n");
return EXIT_FAILURE;
}
使用
sscanf()
转换字符串。例如, char line[] = "John,100";
char name[20];
int score;
if (sscanf(line, "%19[^,],%d", name, &score) != 2) {
fprintf(stderr, "Cannot parse line[] correctly.\n");
return EXIT_FAILURE;
}
在这里,
19
指的是name
中的字符数(始终为字符串末尾nul字符'\0'
保留一个字符),而[^,]
是字符串转换,除了逗号以外都消耗了所有内容。 %d
转换int
。返回值是成功转换的次数。这种方法不修改原始字符串,它允许您尝试许多不同的解析模式。只要先尝试最复杂的一种,就可以允许添加很少代码的多种输入格式。当将2D或3D向量作为输入时,我会定期执行此操作。
缺点是
sscanf()
(scanf系列中的所有函数)会忽略溢出。例如,在32位架构上,最大的int
是2147483647
,但是scanf函数将很乐意转换例如。 9999999999
到1410065407
(或其他值!)而不会返回错误。您只能假设数字输入是合理的并且在限制之内;您无法验证。使用辅助函数来标记和/或解析字符串。
通常,助手功能类似于
char *parse_string(char *source, char **to);
char *parse_long(char *source, long *to);
其中,
source
是指向要分析的字符串中下一个字符的指针,而to
是指向要存储解析的值的指针;要么char *next_string(char **source);
long next_long(char **source);
其中,
source
是指向要解析的字符串中下一个字符的指针,返回值是提取的令牌的值。这些往往比上面的更长,如果是我写的,那么他们接受的输入会有些偏执。 (我想让我的程序抱怨,如果它们的输入不能可靠地解析,而不是无声地产生垃圾。)
如果数据是从文件中读取的CSV(逗号分隔值)的某种变体,则正确的方法是另一种方法:不是逐行读取文件,而是逐个令牌地读取文件。
唯一的“技巧”是记住记号结尾的分隔符(您可以使用
ungetc()
),并使用其他函数(读取和忽略当前记录中的其余记号,并使用)换行符。关于c - 如何将字符串值转换为数值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53690165/