从文件中逐个字符输入,用 C++
有没有办法一次从文件中获取一个数字的输入? 例如,我想将以下整数存储在整数向量中,因为它太长了,甚至不能用 long long int 来保存。
12345678901234567900
那么我如何从文件中读取这个数字,以便我可以:
vector<int> numbers;
number.push_back(/*>>number goes here<<*/)
我知道上面的代码并不完整,但我希望它能解释我正在尝试做的事情。 我也尝试过谷歌,到目前为止它被证明是无效的,因为只有 C 的教程出现了,这并没有真正帮助我太多。
感谢提前, 丹·谢瓦利埃
Is there any way to get input from a file one number at a time?
For example I want to store the following integer in an vector of integers since it is so long and can't be held by even a long long int.
12345678901234567900
So how can I read this number from a file so that I can:
vector<int> numbers;
number.push_back(/*>>number goes here<<*/)
I know that the above code isn't really complete but I hope that it explains what I am trying to do.
Also I've tried google and so far it has proved innefective because only tutorials for C are coming up which aren't really helping me all too much.
Thank is advance,
Dan Chevalier
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可以通过多种方式完成,所有这些方式都可以归结为将每个字符“0”..“9”转换为相应的整数 0..9。以下是如何通过单个函数调用来完成此操作:
从文件读取时,您可以读取字符串和transform(),甚至可以直接从istream迭代器读取transform(),如果该文件中除了您的数字之外没有其他内容:
This could be done in a variety of ways, all of them boiling down to converting each char '0'..'9' to the corresponding integer 0..9. Here's how it can be done with a single function call:
When reading from a file, you could read the string and transform(), or even transform() directly from istream iterators, if there is nothing else in that file besides your number:
在我的脑海中,这应该填充一个字符数组,然后您可以对其进行迭代。我意识到这并不完全是您想要的,但这是我的首选方法。
另外,要对实际数字执行操作,您可以使用:
并在数字足够小以适合数据类型时获取数字,您将数组的每个元素乘以 10 的索引次方相加。
Off the top of my head this should fill up a character array which you can then iterate through. I realize it's not exactly what you were after but it's my preferred method.
Also, to perform operations on the actual numbers you can use:
and to get the number when it is small enough to fit in a datatype you add each element of the array multiplied by 10 to the power of its index.
您可以使用 char c 一次读取一个字符; cin.get(c); 并将其转换为数字
c -= '0'
。但也许您可以将其作为字符串读取或使用类似 BigNum 的内容。You can read a char at a time with
char c; cin.get(c);
and convert it to the numeral withc -= '0'
. But perhaps you can just read it as a string or use something like BigNum.