[英]How to parse a line into different variables in C?
I have a simple file, with integers and characters to be read.我有一个简单的文件,其中包含要读取的整数和字符。 I read line by line and stored them in a char array and then split from the whitespace using strtok() and converted to int variables using atoi(), but I can't extract the single character into a char variable.[![enter image description here][1]][1]我逐行读取并将它们存储在 char 数组中,然后使用 strtok() 从空格中拆分并使用 atoi() 转换为 int 变量,但我无法将单个字符提取到 char 变量中。[![输入图片说明][1]][1]
For starters this code snippet对于初学者,此代码段
fgets(line,255,file);
while (fgets(line,255,file))
{
splitLine(line, 255);
fgets(line,255,file);
splitLine(line, 255);
}
is unsafe because you do not check the result of each call of fgets
.是不安全的,因为您不检查每次调用fgets
的结果。
The second parameter of the function splitLine
is redundant because the first passed argument represents a string函数splitLine
的第二个参数是多余的,因为第一个传递的参数代表一个字符串
So declare the function like所以像这样声明函数
void splitLine( const char line[] );
Within the function it is better to use sscanf
instead of strtok
.在函数中,最好使用sscanf
而不是strtok
。 Moreover for a character symbol to call atoi
does not make a sense此外,对于一个字符符号调用atoi
没有意义
array[count]=atoi(ptr);
The function can look the following way该功能可以如下所示
void splitLine( const char line[] )
{
int rowLength;
int columnLength;
char character;
if ( sscanf( line, "%d %d %c", &rowLength, &columnLength, &character ) == 3 )
{
printf("%d,",rowLength);
printf("%d,",columnLength);
printf("%c\n",character);
}
//...
}
You are doing a different thing for each column, so why use an array?你为每一列做不同的事情,那么为什么要使用数组呢?
char *ptr=strtok(line, " ");
for (count=0; i < 3; i++) {
if (ptr == NULL)
break;
switch(count) {
case 0:
rowlength = atoi(ptr);
break;
case 1:
columnLength = atoi(ptr);
break;
case 2:
character = *ptr;
break;
}
ptr=strtok(NULL, " ");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.