从文件中读取数字并将其转换为 C 中的整数

发布于 2024-12-10 12:44:41 字数 655 浏览 0 评论 0原文

我有一个 FILE 变量,声明为 FILE *fin 。 fin = fopen( "points.dat", "r" ); 在声明后初始化。我一直在尝试循环遍历 fin while fgetc( fin ) != '\n'。这就是我被难住的地方。

我想将 points.dat 第 1 行的每个字符存储到 char * 中,稍后我可以调用 atoi 将其存储为整数。我该怎么做?我已经尝试过了,但我不断收到分段错误和其他奇怪的错误。这是我的最新尝试:

FILE *fin;
char c;
int counter = 0;
int countPoints;
char *readFirst;

fin = fopen( "points.dat", "r" );

while( ( c = fgetc( fin ) ) != '\n' ) {

    readFirst[counter] = c;
    counter++;
}

countPoints = atoi( readFirst );

printf("%d\n", countPoints);

注意:这并不是完整的家庭作业。在我真正完成家庭作业之前,这只是我需要做的一件非常小的事情。

I have a FILE variable, declared as FILE *fin. fin = fopen( "points.dat", "r" ); is initialized after the declaration. I've been trying to loop through fin while fgetc( fin ) != '\n'. Here's where I am stumped.

I want to store each character on line 1 of points.dat into a char *, which I can later invoke atoi on to store as an integer. How should I do this? I've tried it, but I keep getting segmentation faults and other weird errors. Here's my latest attempt:

FILE *fin;
char c;
int counter = 0;
int countPoints;
char *readFirst;

fin = fopen( "points.dat", "r" );

while( ( c = fgetc( fin ) ) != '\n' ) {

    readFirst[counter] = c;
    counter++;
}

countPoints = atoi( readFirst );

printf("%d\n", countPoints);

Note: this is not in its entirity a homework assignment. This is just a very small thing I need to get working before I can actually do the homework assignment.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

计㈡愣 2024-12-17 12:44:41

您没有为 readFirst 分配任何内存,并且它也没有像 C 期望的那样以 NULL 字符终止。

最好使用 fgets 读取字符串并使用 fputs 写入字符串。这样你就不必寻找换行符。
另外,如果您发布写入文件的代码也会很有用。

您还可以使用标准 C++ 文件处理(使用 std::iostream),使工作变得更加容易。

You have not allocated any memory to readFirst and also it is not terminated with NULL character as C expects.

Its better to use fgets to read a string and fputs to write the string. That way you dont have to look for the newline.
Also, it will be useful if you post the code of writing to file.

You could also use standard c++ file handling (using std::iostream), to make the job even easier.

待天淡蓝洁白时 2024-12-17 12:44:41

您遇到分段错误,因为 char *readFirst; 仅声明了一个指针,但它没有保留任何空间来保存数据。

直接将 readFirst 声明为数组 (char readFirst[size];) 或使用函数 malloc() 来分配空间。

You're getting a segmentation fault because char *readFirst; only declares a pointer, but it doesn't reserve any space to hold the data.

Either declare readFirst directly as an array (char readFirst[size];) or use the function malloc() to allocate the space.

大姐,你呐 2024-12-17 12:44:41

readFirst 是一个未初始化的 char 指针。您需要分配一个新的内存块来保存字符,或者将其分配给静态分配的字符数组。另外,如果您要一次读取一个字节的数据,则需要在将字符串传递给 atoi 之前以 null 终止字符串,否则它也会读取到缓冲区末尾和段错误。

看看你是否能从那里弄清楚。如果您需要更多帮助,请给我留言。

readFirst is an uninitialized char pointer. You either need to alloc a new block of memory to hold the characters or assign it to a statically allocated array of chars. Also, if you are going to read the data a single byte at a time, you will need to null terminate the string before passing it into atoi or it will read passed the end of the buffer and segfault as well.

See if you can figure it out from there. If you need more help, message me.

涫野音 2024-12-17 12:44:41

好吧,眼前的问题是您没有为 readFirst 留出任何内存来指向。当您编写 readFirst[counter] = c 时,您试图将 c 的值分配给您可能拥有或不拥有的某个随机内存位置(因此会出现段错误) )。

如果您提前知道数组需要多大,则应该声明 readFirst 因为

char readFirst[SIZE];

它平均需要大约 3.3 位来表示一个十进制数字;将其向下舍入为 3,您可以将数组大小计算为 int 的位宽度除以 3 加上符号和 0 终止符的 2。因此,32 位 int 将需要 9 + 2 = 11 个字符的数组。 64 位整数值需要 22 + 2 = 24。

但这一切都引出了另一个问题:您需要一次读取输入一个字符,然后转换为整数值吗?如果输入文件只是整数的文本表示,您可以绕过整个混乱,只需将 fscanf%d 转换说明符一起使用(尽管这有其自身的一系列问题) )。

或者,您可以使用 fgets 一次读取整个文本字符串,并使用 strtol 转换文本(atoi 不会给您相同的结果)错误处理能力如 strtol)。

Well, the immediate problem is that you haven't set aside any memory for readFirst to point to. When you write readFirst[counter] = c, you're trying to assign the value of c to some random memory location that you may or may not own (hence the segfaults).

If you know how big the array needs to be ahead of time, you should declare readFirst as

char readFirst[SIZE];

It takes roughly 3.3 bits on average to represent a decimal digit; round that down to 3, and you can figure your array size as the bit width of an int divided by 3 plus 2 for the sign and 0 terminator. Thus, a 32 bit int will require an array of 9 + 2 = 11 characters. A 64-bit integer value will require 22 + 2 = 24.

But this all begs another question; do you need to read the input one character at a time and then convert to an integer value? If the input file is simply text representations of integers, you could bypass that whole mess and simply use fscanf with the %d conversion specifier (although that has its own set of issues).

Alternately, you could use fgets to read an entire text string at once and convert the text using strtol (atoi doesn't give you the same error handling capability as strtol).

清风不识月 2024-12-17 12:44:41

当我看到这一点时,您只需使用您的 char 指针而不将其初始化为某些内容。这意味着您的指针指向一些未知的内存区域。如果幸运的话,您会遇到分段错误(这就是为什么将指针初始化为 NULL 是一个好主意),如果没有:欢迎来到未定义领域。

如果你想存储一些东西,你应该首先为它创建一些内存。您可以在堆栈 (char readFirst[size]) 或堆 (malloc()) 上执行此操作。在每种情况下,您都需要事先知道需要多少内存。您需要在编译时(对于堆栈变体)和运行时(对于堆变体)了解这一点。这当然意味着您需要一种方法来找出您需要多少内存。

When I see this right, you just use your char pointer without initializing it to something. That means your pointer points to some unknown memory area. If you are lucky you get a segmentation fault (that's why initializing a pointer to NULL is a good idea), if not: Welcome in the realm of undefinedness.

If you want to store something you should first create some memory for it. You can do that either on the stack (char readFirst[size]) or on the heap (malloc()). In every case you need to know beforehand how much memory you will be needing. You need to know this at compile time for the stack variant and at run time for the heap variant. That of course means that you need a method to find out how much memory you will be needing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文