Ste*_*ris 0 c++ file file-pointer
我想知道我是否可以在文本文件中跳转位置.假设我有这个文件.
12
8764
2147483648
2
-1
Run Code Online (Sandbox Code Playgroud)
每当我尝试读取第三个数字时它就不会读取,因为它大于32位int的最大数字.所以每当我达到第三个数字时,它就会一遍又一遍地读取第二个数字.我怎样才能跳到第4个号码?
使用std :: getline而不是operator >>(std :: istream,int)
std::istream infile(stuff);
std::string line;
while(std::getline(infile, line)) {
int result;
result = atoi(line.c_str());
if (result)
std::cout << result;
}
Run Code Online (Sandbox Code Playgroud)
您遇到自己行为的原因是,当std :: istream尝试(并且失败)读取整数时,它会设置一个"badbit"标志,这意味着出现了问题.只要该badbit标志保持设置,它就不会做任何事情.所以它实际上并没有在那条线上重读,它正在做什么,并留下那些独自存在的价值.如果你想保持与你已经拥有的更多一致,那么它可能就像下面一样.上面的代码更简单,但更不容易出错.
std::istream infile(stuff);
int result;
infile >> result; //read first line
while (infile.eof() == false) { //until end of file
if (infile.good()) { //make sure we actually read something
std::cout << result;
} else
infile.clear(); //if not, reset the flag, which should hopefully
// skip the problem. NOTE: if the number is REALLY
// big, you may read in the second half of the
// number as the next line!
infile >> result; //read next line
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
478 次 |
| 最近记录: |