从文件中读取和打印未签名的int
我正在尝试从.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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从一系列字符到未签名的整数实际上将铸造指针,而不是字符串本身。您需要使用 strtoul()。
不需要替换
'\ n'
字符,因为strtoul停止在第一个字符上停止,这不是有效的数字。我修改了您的功能:
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 :