- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图从 C 语言的文件中读取 double ,但事实证明这是一场噩梦。当我想读取整数或字符时,我似乎没有遇到任何问题,但是 double 似乎很难使用。
所以,假设我有一个包含两列和四行 double 字的文件,我想要两个 vector 来保存每列中的所有数据。我的代码是:
int main(void){
double v1[4],v2[4];
FILE *f;
int i;
f=fopen("hola.rtf","r");
if(f==NULL){
printf("Error fitxer!\n");
exit(1);
}
for(i=0;i<4;i++){
fscanf(f,"%le",&v1[i]);
fscanf(f,"%le",&v2[i]);
printf("%le %le\n",v1[i],v2[i]);
}
fclose(f);
return 0;
但是打印的所有值都是 0...有什么想法/提示吗?
谢谢:)
最佳答案
您没有检查 fscanf()
的返回值,因此您不知道它是否转换(并读取)数据。
此外,double
的说明符对于 printf()
是 %e
(或 %f
或 %g
,具体取决于您想要的格式); %le
不是 C 中的有效说明符,因此如果您的程序打印任何内容,那是因为您的编译器或 C 库接受 %le
。 (不过,无论它理解为什么格式,都可能不是 double
。)
以下是您应该如何阅读 double :
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#define COUNT 4
int main(void)
{
const char *filename = "hola.rtf";
FILE *input;
double v1[COUNT], v2[COUNT];
int i;
input = fopen(filename, "r");
if (!input) {
fprintf(stderr, "Cannot open %s: %s.\n", filename, strerror(errno));
return EXIT_FAILURE;
}
for (i = 0; i < COUNT; i++) {
if (fscanf(input, " %le %le", &(v1[i]), &(v2[i])) != 2) {
fprintf(stderr, "Invalid data in %s.\n", filename);
fclose(input);
return EXIT_FAILURE;
}
printf("Read %e and %e from %s.\n", v1[i], v2[i], filename);
}
if (ferror(input)) {
fclose(input);
fprintf(stderr, "Error reading %s.\n", filename);
return EXIT_FAILURE;
}
if (fclose(input)) {
fprintf(stderr, "Error closing %s.\n", filename);
return EXIT_FAILURE;
}
printf("All %d pairs of doubles read successfully.\n");
return EXIT_SUCCESS;
}
许多程序员认为他们可以稍后再添加错误检查。这是不切实际的;他们通常最终得到的是没有或很少有错误检查的代码。然而,作为用户,您难道不想知道程序何时出现故障并产生垃圾而不是正常结果吗?我确实这样做,我认识的所有使用代码进行实际工作的人也是如此。这是一个需要养成的重要习惯,因为如果你学会不这样做,以后就很难学会这样做。
错误检查的级别当然可以讨论。我相信这里的许多成员都会考虑ferror()
检查并检查 fclose()
的结果为“不必要”。确实,它们在正常、典型的操作中不会失败。程序员有可能永远不会看到它们中的任何一个失败。然而,当它们确实失败时——比如,有人最终在 FUSE 文件系统上运行你的代码,该文件系统可以在关闭时报告错误——检查可能意味着大量垃圾和出现问题的早期警告之间的区别。
如果您碰巧同意我的观点(关于半偏执的错误检查是良性的,有时对用户非常有用),请考虑您的代码的以下变体,它从命令行指定的文件中读取所有双对到动态分配的数组:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
typedef struct {
double x;
double y;
} vec2d;
/* Read all 2D vectors from stream 'input',
into a dynamically allocated array.
(Similar to POSIX.1 getline(), but with double vectors.)
If *dataptr is not NULL, and *sizeptr > 0,
it will initially be used (but reallocated if needed).
Returns the number of vectors read,
or 0 with errno set if an error occurs.
*/
size_t vec2d_readall(FILE *input, vec2d **dataptr, size_t *sizeptr)
{
vec2d *data;
size_t size;
size_t used = 0;
if (!input || !dataptr || !sizeptr) {
/* At least one of the parameters is NULL. */
errno = EINVAL;
return 0;
}
if (ferror(input)) {
/* input stream is already in error state. */
errno = EIO;
return 0;
}
if (!*dataptr || !*sizeptr) {
/* *dataptr is NULL, or *sizeptr == 0,
so we initialize them to empty. */
*dataptr = NULL;
*sizeptr = 0;
}
data = *dataptr;
size = *sizeptr;
while (1) {
if (used >= size) {
/* We need to grow the data array. */
/* Simple allocation policy:
allocate in sets of roughly 1024 vectors. */
size = (used | 1023) + 1021;
data = realloc(data, size * sizeof *data);
if (!data) {
/* Realloc failed! */
errno = ENOMEM;
return 0;
}
*dataptr = data;
*sizeptr = size;
}
if (fscanf(input, " %lf %lf", &(data[used].x), &(data[used].y)) != 2)
break;
/* One more vector read successfully. */
used++;
}
/* If there was an actual I/O error, or
the file contains unread data, set errno
to EIO, otherwise set it to 0. */
if (ferror(input) || !feof(input))
errno = EIO;
else
errno = 0;
return used;
}
因为vec2d_readall()
函数总是设置errno
(如果没有发生错误,则为 0
),使用上述函数从标准输入中读取所有 double 对作为 2D vector 非常简单:
int main(void)
{
vec2d *vectors = NULL;
size_t num_vectors = 0;
size_t max_vectors = 0;
size_t i;
num_vectors = vec2d_readall(stdin, &vectors, &max_vectors);
if (errno) {
fprintf(stderr, "Standard input: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
printf("Read %zu vectors from standard input,\n", num_vectors);
printf("with memory allocated for up to %zu vectors.\n", max_vectors);
for (i = 0u; i < num_vectors; i++)
printf("%f %f\n", vectors[i].x, vectors[i].y);
return EXIT_SUCCESS;
}
在写作上花费了一点额外的努力vec2d_readall()
简化了我们的main()
很多。另外,如果我们发现需要类似的函数来读取 3D vector ,我们只需要添加 typedef struct { double x; double y; double z } vec3d;
,并对 vec2d_readall()
进行一些非常小的更改将其变成 vec3d_readall()
.
最重要的是,我们可以信赖vec2d_readall()
如果数据存在任何类型的问题,则失败。我们可以添加错误报告,而不仅仅是 break;
跳出循环。
如果您想知道 getline()
在评论中提到,它是一个 POSIX.1-2008 标准函数,允许 POSIXy 系统中的 C 程序员读取无限长度的输入行。它类似于 fgets()
,但具有动态内存管理。
关于c - 在 C 中读取文件中的 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45142860/
我想做的是让 JTextPane 在 JPanel 中占用尽可能多的空间。对于我使用的 UpdateInfoPanel: public class UpdateInfoPanel extends JP
我在 JPanel 中有一个 JTextArea,我想将其与 JScrollPane 一起使用。我正在使用 GridBagLayout。当我运行它时,框架似乎为 JScrollPane 腾出了空间,但
我想在 xcode 中实现以下功能。 我有一个 View Controller 。在这个 UIViewController 中,我有一个 UITabBar。它们下面是一个 UIView。将 UITab
有谁知道Firebird 2.5有没有类似于SQL中“STUFF”函数的功能? 我有一个包含父用户记录的表,另一个表包含与父相关的子用户记录。我希望能够提取用户拥有的“ROLES”的逗号分隔字符串,而
我想使用 JSON 作为 mirth channel 的输入和输出,例如详细信息保存在数据库中或创建 HL7 消息。 简而言之,输入为 JSON 解析它并输出为任何格式。 最佳答案 var objec
通常我会使用 R 并执行 merge.by,但这个文件似乎太大了,部门中的任何一台计算机都无法处理它! (任何从事遗传学工作的人的附加信息)本质上,插补似乎删除了 snp ID 的 rs 数字,我只剩
我有一个以前可能被问过的问题,但我很难找到正确的描述。我希望有人能帮助我。 在下面的代码中,我设置了varprice,我想添加javascript变量accu_id以通过rails在我的数据库中查找记
我有一个简单的 SVG 文件,在 Firefox 中可以正常查看 - 它的一些包装文本使用 foreignObject 包含一些 HTML - 文本包装在 div 中:
所以我正在为学校编写一个 Ruby 程序,如果某个值是 1 或 3,则将 bool 值更改为 true,如果是 0 或 2,则更改为 false。由于我有 Java 背景,所以我认为这段代码应该有效:
我做了什么: 我在这些账户之间创建了 VPC 对等连接 互联网网关也连接到每个 VPC 还配置了路由表(以允许来自双方的流量) 情况1: 当这两个 VPC 在同一个账户中时,我成功测试了从另一个 La
我有一个名为 contacts 的表: user_id contact_id 10294 10295 10294 10293 10293 10294 102
我正在使用 Magento 中的新模板。为避免重复代码,我想为每个产品预览使用相同的子模板。 特别是我做了这样一个展示: $products = Mage::getModel('catalog/pro
“for”是否总是检查协议(protocol)中定义的每个函数中第一个参数的类型? 编辑(改写): 当协议(protocol)方法只有一个参数时,根据该单个参数的类型(直接或任意)找到实现。当协议(p
我想从我的 PHP 代码中调用 JavaScript 函数。我通过使用以下方法实现了这一点: echo ' drawChart($id); '; 这工作正常,但我想从我的 PHP 代码中获取数据,我使
这个问题已经有答案了: Event binding on dynamically created elements? (23 个回答) 已关闭 5 年前。 我有一个动态表单,我想在其中附加一些其他 h
我正在尝试找到一种解决方案,以在 componentDidMount 中的映射项上使用 setState。 我正在使用 GraphQL连同 Gatsby返回许多 data 项目,但要求在特定的 pat
我在 ScrollView 中有一个 View 。只要用户按住该 View ,我想每 80 毫秒调用一次方法。这是我已经实现的: final Runnable vibrate = new Runnab
我用 jni 开发了一个 android 应用程序。我在 GetStringUTFChars 的 dvmDecodeIndirectRef 中得到了一个 dvmabort。我只中止了一次。 为什么会这
当我到达我的 Activity 时,我调用 FragmentPagerAdapter 来处理我的不同选项卡。在我的一个选项卡中,我想显示一个 RecyclerView,但他从未出现过,有了断点,我看到
当我按下 Activity 中的按钮时,会弹出一个 DialogFragment。在对话框 fragment 中,有一个看起来像普通 ListView 的 RecyclerView。 我想要的行为是当
我是一名优秀的程序员,十分优秀!