将文件中的一组字符转换为 int
我正在阅读:
22:5412:99:00 (...)
使用 (ch=fgetc(fp)) != EOF
从文本文件中读取,因为我不仅要读取这些数字。 使用 if(ch >= 48 && ch <= 57)
识别数字很容易,但问题是我想将这些数字 22、5412 放入整数数组中。但是,当我读取字符时,它会读取数字的一部分,因为每个数字都是字符。 它得到 2(而不是像我想要的那样 22),并在下一次迭代中读取其他 2。如何将每组数字保存到它自己的整数中?
我希望我说得足够清楚,谢谢!
I'm reading:
22:5412:99:00 (...)
From a text file using (ch=fgetc(fp)) != EOF
because I don't have only those numbers to read.
Identifying a number is easy with if(ch >= 48 && ch <= 57)
but the thing is I want to put those numbers 22, 5412 into an array of integers. However when I read a char it reads part of number since each number is char.
It gets 2 (and not 22 like I want to) and in the next iteration reads the other 2. How can I save each set of numbers into it's own integer?
I hope I was clear enough, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的想法是读取每个
char
,如果它是数字,则将其附加到缓冲区。每当我们得到一个非数字时,我们只需使用 sscanf 将缓冲区的内容作为字符串读取,并清除缓冲区以获取下一个值。My idea is to read in each
char
, and if it is a digit append it to a buffer. Whenever we get a non-digit, we just read the contents of the buffer as a string usingsscanf
, and clear the buffer for the next value.您需要将数字存储为字符串或 char* 并使用 atoi 将其实际转换为数字。 http://www.cplusplus.com/reference/clibrary/ cstdlib/atoi/
You would need to store the numbers as a string or a char* and use atoi to actually convert it to a number. http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
假设您的模式是
NN:NNNN:NN:NN
类型,解析分隔符,将字符输入缓冲区:Assuming your pattern is of the type
NN:NNNN:NN:NN
, parse on the delimiter, feeding characters into a buffer:我在上一篇文章中做了一个完整的程序——以及一些测试:-)
和测试运行
I did a full program out of the previous post -- and some testing :-)
And a test run