C 如何将字符串拆分为单词?
我有一个文件,其中有3列和数据。我没有列标题,只有数据。C 如何将字符串拆分为单词?,c,arrays,C,Arrays,我有一个文件,其中有3列和数据。我没有列标题,只有数据。 我的文件是这样的: 现在我想读取文件中的数据,并用它画一个条形图。但是我在读取数据时遇到了困难。我的逻辑是将文件内容存储在一个数组中,使用\n拆分该数组,以便将每一行存储到另一个数组中。然后用拆分新阵列以向不同的列发送信号 这是我的函数,它将数据文件作为参数: #include "visualiser.h" #include <stdio.h> #include <stdlib.h> #include<st
我的文件是这样的: 现在我想读取文件中的数据,并用它画一个条形图。但是我在读取数据时遇到了困难。我的逻辑是将文件内容存储在一个数组中,使用
\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);
}
#包括“visualiser.h”
#包括
#包括
#包括
#包括
#定义LSIZ 128
#定义RSIZ 10
无效密码文件(char*arr);
int main(int argc,字符**argv){
初始接口(“银色”、“蓝色”);
如果(argc考虑读一行。
使用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");
}
请将输入数据显示为格式化为代码块的文本。请添加足够的代码并删除不必要的部分,以允许编译和运行您的程序。(添加main
函数或从passFile
创建main
,删除对waitExit
和appendRow
等无趣函数的所有调用。)再给我一点时间好的,我会尽快更新帖子now@user3121023我已经发布了更改和新输出,请发布一个。如果不对此处未包含的部分进行假设,则无法调试代码,因为这些部分很可能是错误的。