从文件中读取和打印未签名的int

发布于 2025-02-09 17:00:25 字数 568 浏览 5 评论 0原文

我正在尝试从.txt文件打印和读取未签名的INT。我正在使用FPRINTF打印无计划的INT(Menualy检查文件显示想要的值),但是在阅读它时,我会偏向于所有阅读的值(在所有读取之间相同的偏移),但并非每次读取,但不是程序),这是我正在使用的读取代码:

unsigned int tempDuration = (unsigned int)fileFgets(file);

这是filefgets:

char tempStr[MAX_STR_SIZE] = { 0 };
char* str = 0;
fgets(tempStr, MAX_STR_SIZE, file);
tempStr[strcspn(tempStr, "\n")] = 0;
str = (char*)malloc(strlen(tempStr) * sizeof(str));
strcpy(str, tempStr);
return str;

我正在使用此函数,因为读取字符串和未播放的ints是'\ n'的,但很开放,可以使用奇异的解决方案。或任何一个。 (读取字符串按预期工作)

I am trying to print and read unsigned ints from a .txt file. I am using fprintf to print the unsigend int, (menualy checking the file presents the wanted values), but when reading it, I get a weird offset to all the values I read (same offset beween all reads, but not every run of the program), here is the reading code I am using:

unsigned int tempDuration = (unsigned int)fileFgets(file);

and this is fileFgets:

char tempStr[MAX_STR_SIZE] = { 0 };
char* str = 0;
fgets(tempStr, MAX_STR_SIZE, file);
tempStr[strcspn(tempStr, "\n")] = 0;
str = (char*)malloc(strlen(tempStr) * sizeof(str));
strcpy(str, tempStr);
return str;

I am using this function becuse it is ment to read both strings and unsinged ints, seperated by '\n', but am open for using diffrent solutions for both or either. (reading the strings works as intended)

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

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

发布评论

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

评论(1

猫九 2025-02-16 17:00:25

从一系列字符到未签名的整数实际上将铸造指针,而不是字符串本身。您需要使用 strtoul()

不需要替换'\ n'字符,因为strtoul停止在第一个字符上停止,这不是有效的数字。

我修改了您的功能:

unsigned int fileFgets(file)
{
    char tempStr[MAX_STR_SIZE] = { 0 };
    fgets(tempStr, MAX_STR_SIZE, file);
    return strtoul(tempStr, NULL, 0);
}

Casting from an array of characters to an unsigned integer will actually cast the pointer and not the string itself. You need to convert it using strtoul().

Replacing the '\n' character isn't required because strtoul stopps at the first character which is not a valid digit.

I modified your function :

unsigned int fileFgets(file)
{
    char tempStr[MAX_STR_SIZE] = { 0 };
    fgets(tempStr, MAX_STR_SIZE, file);
    return strtoul(tempStr, NULL, 0);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文