[英]fgets() reads and stores a char form a line twice
所以我有一個文件data.txt
,其中寫入了隨機整數,例如"17 12 5 4 16"
。
因此,我使用fgets()
讀取這行整數並將其存儲在char str []
。 正如預期的那樣str [0] == 17
,但str [1] == 7
,依此類推......整數每兩位數存儲在數組中的一個元素中,但第二個數字也存儲在以下元素中.
示例: str [3] = 12
, str [4] = 2
, str[5] = ' '
。
可以做些什么來解決這個問題?
這是我非常典型的代碼:
FILE* fp = fopen ("data.txt", "r");
int i = 0, j = 0;
int size = fileSize(fp) + 1; // Enumerate the char numbers in file
char str [size];
rewind (fp);
fgets (str, size, fp);
這是我的全部代碼
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct RATIONAL
{
int top;
int bottom;
} RATIONAL;
void printArray (int arr [], int count)
{
for (int i = 0; i < count; ++i)
{
printf ("%d\n", arr[i]);
}
}
int fileSize (FILE* fp)
{
char c;
int i = 0;
while ((c = getc (fp)) != EOF)
{
i++;
}
return (i);
}
int main ()
{
RATIONAL ratArray [23]; //array to hold rational numbers
int intArray [45]; //array to hold integer values
FILE* fp = fopen ("data.txt", "r");
int i = 0, j = 0;
int size = fileSize(fp) + 1; // Enumerate the char numbers in file
char str [size];
rewind (fp);
fgets (str, size, fp);
//Convert string to array of ints
while (i < size -1)
{
if (isdigit (str [i]))
{
intArray[j++] = atoi(&str[i]);
i++;
}
else
i++;
}
printArray (intArray, intArray[0]);
輸入: data.txt
您所體驗到的絕對是意料之中的。 關鍵的誤解是您希望arr[N]
保存第 (N+1)個整數,因為它是一個整數數組……但事實並非如此。 它是一個字符數組。
如果將整數存儲在char
數組中,則每個數字都將占用一個數組位置。 因此arr[0]
將包含第一個數字的最高有效數字,而arr[a]
將包含最低有效數字。
因此,在您的示例中,字符串"17 12 5 4 16"
將以這種方式存儲:
--------------------------------------------------------------------------------------------
| 0x31 | 0x37 | 0x20 | 0x31 | 0x32 | 0x20 | 0x35 | 0x20 | 0x34 | 0x20 | 0x31 | 0x36 | 0x00 |
--------------------------------------------------------------------------------------------
| '1' | '7' | ' ' | '1' | '2' | ' ' | '5' | ' ' | '4' | ' ' | '1' | '7' | '\0' |
--------------------------------------------------------------------------------------------
所有數字都在同一個數組中並用空格分隔。 該字符串由字符串終止符'\\0'
關閉。
有趣的是,如果你用printf("%s\\n", arr)
打印整個字符串,你會得到
17 12 5 4 16
但是如果你嘗試打印傳遞第二個字符的地址,你會得到printf("%s\\n", &arr[1])
7 12 5 4 16
等等。 這意味着C 不知道(還不知道)您的意圖是存儲 5 個 integers 。 字符串是一個直到找到字符串終止符(空格不會終止字符串),所以從第二個數字開始只會讓 C 打印除第一個數字之外的所有字符串。
由於您有一個以眾所周知的方式格式化的字符串並且您想要一個整數數組,因此您必須解析它以獲取整數:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char arr[] = "7 12 5 4 16";
int main()
{
char * token = strtok(arr, " ");
while(token != NULL)
{
printf("Next int: %d %s\n", atoi(token)); // Here you can assign the value to your array
token = strtok(NULL, " ");
}
return 0;
}
在我的演示示例中,輸入字符串是一個全局數組,而不是像您的場景中那樣從文件中讀取的內容,我使用了strtok() ( strtok_r
需要可重入函數,可以使用strtok_r
)並且我得到了使用簡單的atoi()
整數(只是因為輸入格式是 _under control - 我建議使用strtol()
來更好地控制輸入)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.