处理文件中的字符串
Handling strings inside Files
我正试图将数据从文件保存到数组中,但我现在没有运气。从文件中读取数据后保存数据很容易,以防数据只是数字,但如果我试图保存字符串,程序就会一次又一次地崩溃。我使用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::vector
和std: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或更少。
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 将二进制字符串/文件内容从 c++ 传递到节点 js
- 在字符串.h文件中调用函数而不带对象
- 将带有引号和逗号的字符串文件读入字符串数组
- 如何从字符串/文件中分离字符和整数
- 将字符串文件存储到动态数组中
- 如何用C++将字符串文件Txt解析成数组
- 如何用Boost::Spirit解析复杂的字符串文件
- 如何从C语言的第二行读取字符串文件
- 一个很好的性能替代PHP-字符串/文件操作