处理文件中的字符串

Handling strings inside Files

本文关键字:字符串 文件 处理      更新时间:2023-10-16

我正试图将数据从文件保存到数组中,但我现在没有运气。从文件中读取数据后保存数据很容易,以防数据只是数字,但如果我试图保存字符串,程序就会一次又一次地崩溃。我使用fscanf();函数,因为整个。txt文件都以相同的格式编写:"First Name, Last Name"。现在,我试着这样使用for循环:

char *firstName = (char*)malloc(sizeof(char)*10240);
char *lastName = (char*)malloc(sizeof(char)*10240);
for(int i = 0; i<10; i++){
    fscanf(fp, "%s %s", firstName[i],lastName[i]);
}

这就是它崩溃的地方

纯C代码:

您必须首先分配数组的数组,然后逐个分配每个字符串最好将字符串扫描为大尺寸的临时字符串,然后复制字符串。

int i,nb_names = 10;
char **firstName = malloc(sizeof *firstName * nb_names);
char **lastName = malloc(sizeof *lastName *nb_names);
char tempn[1000],templ[1000];
for(i = 0; i<nb_names; i++){
    fscanf(fp,"%s %s", tempn,templ);
    firstName[i] = strdup(tempn);
    lastName[i] = strdup(templ);
}

请注意,我已将for (int i更改为for (i,因为它不兼容C,而是兼容c++(或C99,不确定)。对于c++,放弃malloc,使用std::vectorstd:string

如果可以的话,我建议使用c++。我回答了很多关于人们尝试(和失败)正确分配2D数组的C/c++问题(包括我5分钟前该死的:))。使用c++库的c++代码更清晰。

完整c++示例,从标准输入

读取
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int nb_names = 10;
vector<string > firstName(nb_names);
vector<string > lastName(nb_names);
for(int i = 0; i<nb_names; i++){
    cin >> firstName[i]; 
    cin >> lastName[i];
}
return 0;
}

代码中的错误是:firstName[i]是一个字符而不是字符串,但您使用%s而不是%c将其用作字符串。

应该使用char **而不是char *。

char **firstName = (char**)malloc(10*sizeof(char)*10240);

我也认为10240对于firstName来说太大了。使用255或更少。