c - 我对 C 编程有点陌生。我需要帮助将文件(test.txt)中的字符串推送到不带逗号的数组中
问题描述
我试图通过 malloc(),free(),realloc() 从文件读取输入来解决动态内存分配问题;我只需要帮助将字符串从文件中推送到数组中,而不需要逗号。我的 test.txt 文件如下:
一,5,0
一,25,1
一,1,2
r,10,1,3
f,2
int i;
int count;
char line[256];
char *str[20];//to store the strings without commas
char ch[20];
int main (void)
{
FILE *stream;
if ( (stream = fopen ( "test.txt", "r" )) == NULL )
{ printf ("Cannot read the new file\n");
exit (1);
}
while(fgets(line, sizeof line, stream))
{
printf ("%s", line);
int length = strlen(line);
strcpy(ch,line);
for (i=0;i<length;i++)
{
if (ch[i] != ',')
{
printf ("%c", ch[i]);
}
}
}
//i++;
//FREE(x);
//FREE(y);
//FREE(z);
fclose (stream);
str[] 数组应该只存储像 a520 这样的值。(不包括逗号)
解决方案
首先,除非绝对需要,否则不要使用全局变量。我假设您希望 str 作为指针数组,而 str[0] 存储第一行,str[1] 存储第二行,依此类推。为了这:
int line_pos = 0; //stores line_number
int char_pos = 0; //stores position in str[line_pos]
while(fgets(line, sizeof(line), stream))
{
printf ("%s", line);
int length = strlen(line);
strcpy(ch,line);
str[line_pos] = calloc(length, sizeof(char)); //allocating memory
for (i=0;i<length;i++)
{
if (ch[i] != ',')
{
*(str[line_pos]+char_pos) = ch[i]; //setting value of str[line][pos]
char_pos++;
}
}
char_pos = 0;
line_pos++;
}
printf("%s", str[0]); //print first line without comma
请注意,它仅适用于 20 行(因为您声明了 *str[20]),然后对于第 21 行或之后的行,它会导致溢出并可能导致各种灾难。您可以包括:
if (line_pos >= 20)
break;
作为安全措施。
请注意,为 str 分配了稍微多一点的内存(分配的内存 = memory_required + 逗号数)。为了防止这种情况,您可以设置ch
为不带逗号的文本:
for (i=0;i<length;i++)
{
int j = 0; //stores position in ch
if (line[i] != ',')
{
ch[j++] = line[i];
}
然后为 str[line_pos] 分配内存,例如:
str[line_pos] = calloc(strlen(ch0, sizeof(char));
推荐阅读
- javascript - 如何链接纽曼测试运行?
- google-cloud-platform - Dialogflow Google 日历集成“错误:WebhookClient.handleRequest 处没有请求意图的处理程序”
- sql - 添加一列,其中包含客户通过订单时的订单数
- javascript - 暂停点击率低于自然关键字的付费关键字的 Google Ads 脚本
- c++ - 我是 C++ 的初学者,我在学习递归时无法理解 blob 着色的结果
- node.js - 循环不等待在节点 js 中执行查询
- python - Pycharm中没有选择Python解释器(也没有选择项目)
- css - 背景图像在较小的屏幕尺寸上变为椭圆形
- c# - 如何使用旧的 Microsoft.WindowsAzure .NET SDK 为 Azure Blob 访问创建用户委托 SAS 密钥?
- tensorflow - TensorFlow 和 TFLite - 准确性/运行时损失