テキストファイル内の位置をジャンプできるかどうか疑問に思っていました。このファイルがあるとします。
12
8764
2147483648
2
-1
32 ビット int の最大数よりも大きいため、3 番目の数値を読み込もうとすると、読み取れません。どうすれば4番目の数字にジャンプできますか?
テキストファイル内の位置をジャンプできるかどうか疑問に思っていました。このファイルがあるとします。
12
8764
2147483648
2
-1
32 ビット int の最大数よりも大きいため、3 番目の数値を読み込もうとすると、読み取れません。どうすれば4番目の数字にジャンプできますか?
operator>>(std::istream, int) の代わりに std::getline を使用します
std::istream infile(stuff);
std::string line;
while(std::getline(infile, line)) {
int result;
result = atoi(line.c_str());
if (result)
std::cout << result;
}
このような動作が発生している理由は、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
}
を使用する代わりにstd::getline()
、を呼び出すことができますstd::ios::clear()
。前の質問からのこの抜粋を検討してください
fin >> InputNum;
そのコードを次のように置き換えることができます。
fin >> InputNum;
if(!fin)
fin.clear();
最初に行を読み取ってから、可能であれば行を整数に変換できます。ファイルの例を次に示します。
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream in("file");
std::string line;
while (std::getline(in, line)) {
int value;
std::istringstream iss(line);
if (!(iss >> value)) {
std::istringstream iss(line);
unsigned int uvalue;
if (iss >> uvalue)
std::cout << uvalue << std::endl;
else
std::cout << "Unable to get an integer from this" << std::endl;
}
else
std::cout << value << std::endl;
}
}