[英]Reading a txt file
对于我的项目,我必须覆盖operator >>方法以从文本文件中读取数字数组。 这是我第一次做任何事情,我很失落。 到目前为止,我的代码看起来像这样。
std::istream& operator>>(std::istream& in, bigint array){
bool semi = false ;
while(!semi){
if(get() = ';')
semi = true ;
in <<get();
}
return in ;
}
文件看起来像这样。
10000000000000000000000000000000000345;
299793000000
00000000000000000000067;
4208574289572473098273498723475;
28375039287459832728745982734509872340985729384750928734590827098752938723;
99999999; 99999999;
每个新数组都在命中";'
时停止 。空白和结尾行也使我感到困惑,任何帮助,谢谢。
您将要使用
bigint& array
以通过引用获取值(或者您不可能将读取的数字插入其中)。
另外,您将需要使用
char ch;
in >> ch;
而不是in << get()
(不会编译)。 更好的是,添加错误处理:
if (!(in >> ch))
{
// we're in trouble (in.rdstate(), in.eof(), in.fail() or in.bad() to know more)
}
如果要使用in.get()
,则应该准备跳过自己的空格(包括换行符)。 我在这里更喜欢std::istream_iterator
,因为它将自动执行此操作(如果std::ios::skipws
标志有效,默认情况下为std::ios::skipws
)。
因此,这是一种简化列表方法(主要假设输入数据有效且空白可忽略):
#include <vector>
#include <istream>
#include <iterator>
struct bigint
{
std::vector<char> v; // or whatever representation you use (binary? bcd?)
};
std::istream& operator>>(std::istream& in, bigint& array)
{
for (std::istream_iterator<char> f(in), l; f != l; ++f) {
if (*f>='0' && *f<='9')
array.v.push_back(*f - '0');
else if (*f==';')
break;
else
throw "invalid input";
}
return in;
}
#include <iostream>
#include <sstream>
int main()
{
std::istringstream iss(
"10000000000000000000000000000000000345;\n"
"299793000000\n"
"00000000000000000000067;\n"
"4208574289572473098273498723475;\n"
"28375039287459832728745982734509872340985729384750928734590827098752938723;\n"
"99999999; 99999999;\n");
bigint value;
while (value.v.clear(), iss >> value)
std::cout << "read " << value.v.size() << " digits\n";
}
这里有很多困惑。 我只列出一些要点,但是即使您修复了这些问题,您也有一条路要走。
你到底在读什么书? 您说您正在读取数字数组,但是您的代码说明了这一点
std::istream& operator>>(std::istream& in, bigint array){
我可能是错的,但是bigint
在我看来像一个数字。 我希望这样的事情
std::istream& operator>>(std::istream& in, std::vector<bigint>& array){
到第二点,操作符>>应该修改它的第二个参数,这意味着它不能按值传递,必须使用引用。 换句话说这是错误的
std::istream& operator>>(std::istream& in, X x){
但这没关系
std::istream& operator>>(std::istream& in, X& x){
您正在尝试读取一个bigint数组,因此需要一个循环(您有一个循环),每次循环时您将读取一个bigint。 因此,您需要一种阅读bigint的方法,您有吗? 您的问题或代码中没有任何内容表明您具有读取bigint的能力,但是显然这样做至关重要。 因此,如果您还没有任何代码可以读取bigint,则可以在拥有该代码之前就忘记整个练习,因此请首先进行操作。 当您可以读取一个bigint时,才应该回到读取一组bigint的问题。
另一个棘手的部分是停止条件,您在读取分号时停止(可能在空格之后)。 所以,你需要一种方法来读取下一个非空格字符,也是至关重要的一点,你需要一种方法,如果原来不是一个分号来未读它。 所以你需要这样的东西
if (!(in >> ch) || ch == ';') { // quit, either no more input, or the next char is a semicolon break; } in.putback(ch); // unread the last char read // read the next bigint
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.