gpt4 book ai didi

c - 如何将字符串拆分为单词?

转载 作者:行者123 更新时间:2023-11-30 20:29:22 25 4
gpt4 key购买 nike

我有一个包含 3 列和数据的文件。我没有列标题,只有数据。
我的文件是这样的:

Data

现在我想读取文件中的数据,并用它绘制条形图。但我在读取数据时遇到问题。我的逻辑是将文件内容存储在一个数组中,用 \n 拆分数组,以便将每一行存储到另一个数组中。然后用 分割新数组以表示不同的列。

这是我的函数,它将数据文件作为参数:

#include "visualiser.h"
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <unistd.h>
#define LSIZ 128
#define RSIZ 10
void passFile(char *arr);

int main(int argc, char **argv){
initInterface("silver","blue");
if(argc <2){
passFile("data-file.txt");
}
if(argc == 2){
passFile(argv[1]);
} else {
printf("Invalid arguments");
exit(0);
}
return 0;
}

void passFile(char *arr){
char line[RSIZ][LSIZ];
char fname[20];
int i = 0;
int tot = 0;
int waitingTime = 0;
int finishTime = 0;
FILE *fptr = NULL;
fptr = fopen(arr, "r");
while(fgets(line[i], LSIZ, fptr)){
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
tot = i;
printf("\n The content of the file %s are : \n",arr);
for(i = 0; i < tot; ++i){
char str[18];
strncpy(str,line[i],18);
const char s[2] = "\n";
char *token;
/* get the first token */
token = strtok(str, s);
for(int j=0;j<3;j++){
char str1[18];
int arrivalTime;
int serviceTime;
strncpy(str1,token,18);
const char s1[2] = " ";
char * pch;
// printf ("Splitting string \"%s\" into tokens:\n",str1);
pch = strtok (str1,s1);
sscanf (line[i], "%17s %d %d", str1, &arrivalTime, &serviceTime);
appendRow(str1); //get the first column name
appendBar(i+1,serviceTime,"black"," ",0);
}



/* walk through other tokens */
while(token != NULL ) {
// printf( " %s\n", token);
token = strtok(NULL, s);
}

}
printf("\n");
// printf("The file has %d lines", processCount);
sleep(100);
waitExit();
fclose(fptr);
}

现在我在图表上绘制了条形图。然而,它们是重复的,并且值都是错误的。例如,第一个条的长度应为 3,但这是输出:

Graph output

最佳答案

考虑读取一行。
使用 sscanf 解析该行。 sscanf 返回的将是扫描的项目数。如果扫描了三个项目,则处理它们。
fgets 将在文件末尾返回 NULL 并终止循环。

下面是执行此操作的代码:

void passFile(char *arr){
char line[LSIZ];
char fname[20];
char str[18];
int arrivalTime;
int serviceTime;
int i = 0;
FILE *fptr = NULL;
if ( NULL != ( fptr = fopen(arr, "r"))) {
while ( fgets ( line, LSIZ, fptr)){
if ( 3 == sscanf ( line, "%17s %d %d", str1, &arrivalTime, &serviceTime)) {
appendRow ( str1);
appendBar ( i + 1, serviceTime, "black", " ", 0);
i++;
}
}
sleep(100);
waitExit();
fclose(fptr);
}
printf("\n");
}

关于c - 如何将字符串拆分为单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58301462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com