我的程序收到具有以下格式的字符串:
char* s = "(char)=(int1)+(int2)"
像char* s = "x=11+12"
并且我需要将两个整数转换为两个变量,例如var1
和var2
。
我正在迭代字符串,但是它对大于9的数字无效。
示例:
char* buffer = NULL;
size_t buffsize = 32;
ssize_t aux;
FILE *fp;
fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("FILE ERROR\n");
return 0;
}
aux = getline(&buffer, &buffersize, fp);
//aux = "x=2+10"
fclose(fp);
我希望var1 = 2
; var2 = 10
答案 0 :(得分:0)
这是使用sscanf
函数的简单解决方案。
#include <stdio.h>
#include <stdlib.h>
int main( int argc,char *argv[])
{
int var1,var2;
char *buffer=NULL,c;
size_t bufsize = 32;
size_t characters;
FILE *fp;
if( argc != 2)
return -1;
buffer = (char *)malloc(bufsize * sizeof(char));
fp = fopen(argv[1],"r");
if( fp == NULL)
return -2;
characters = getline(&buffer,&bufsize,fp);
buffer[characters-1]='\0';
sscanf( buffer, "aux = \"%c=%d+%d\"",&c,&var1, &var2 );
printf("var1 = %d , var2 = %d \n",var1,var2);
return 0;
}