[英]Parse 2d character array
I have a text file as follows: 我有一个文本文件,如下所示:
Rank Title Weekend Box Office 排名标题周末票房
1 American Sniper $31,850,000 1名美国狙击手$ 31,850,000
2 Paddington $8,505,000 2帕丁顿(Paddington)$ 8,505,000
I put each line into a 2d character array. 我将每一行放入一个二维字符数组。 I want to separate each line and put all the ranks in one array, all the titles in another array and all the weekend box office's in another. 我想将每一行分开,将所有排名放在一个数组中,将所有标题放在另一个数组中,将所有周末票房放在另一个数组中。
How do you go about parsing the char data[5][200]
such that I can get the string value only. 如何解析char data[5][200]
这样我只能得到字符串值。 I was thinking along the lines of the %s specifier, but I don't know which method to use it with (new to c). 我一直在考虑%s的说明符,但是我不知道使用哪种方法(c的新手)。
//-------Text File Implementation-----------
FILE *fp;
char data[5][200];
/* opening file for reading */
fp = fopen("movie.txt", "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
int i = 0;
while(fgets (data[i], 200, fp)!=NULL)
{
/* writing content to stdout */
puts(data[i]);
i+=1;
}
fclose(fp);
You can parse using strtok() 您可以使用strtok()进行解析
Here you can read each line in, then tokenize. 在这里您可以读入每一行,然后标记化。 This is an example that you can try out. 这是一个可以尝试的示例。
#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
char text[255] = "1 American Sniper $31,850,000";
const char *rank = strtok(text, " ");
const char *name = strtok(NULL, "$");
const char *amount = strtok(NULL, "\n");
printf("%s|%s|%s\n", rank, name, amount);
}
This outputs "1|American Sniper |31,850,000". 这将输出“ 1 |美国狙击手| 31,850,000”。 You'll lose the $ sign, but you can add it back easily. 您会丢失$符号,但可以轻松将其重新添加。
For the rest of your code structure, I'd recommend creating a single line buffer to read each line in and process it separately, then just keep the tokens after that. 对于您的其余代码结构,我建议创建一个行缓冲区以读取每一行并分别处理它,然后在此之后保留标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.