I have a file with a sequence of int numbers. It is necessary to read one number at a time in order to carry out manipulations with it. The documentation states that the in.get() method returns an int_type . What does this type mean?

 std::ifstream in("in.txt"); std::cout << in.get(); // печатает код первого символа файла, а надо первое число 
  • To copy numbers to a vector from a text file, you can istream_iterator<int> . - jfs
  • @jfs yes, but I still need to manipulate them as they are read - bob
  • manipulate, nothing bothers you. What do you think stl algorithms that take first, last InputIterator do. - jfs

2 answers 2

It seems that the numbers in your file are stored in a textual representation and you read them incorrectly. In fact, you are reading a text file character by character, getting the numeric code of the characters read. Instead, you need to read up to the first whitespace and convert the resulting string to an integer. To do this, you can use the read statement from the stream.

 #include <iostream> #include <fstream> int main(int argc, char *argv[]) { std::ifstream in("in.txt"); if (in.is_open()) { int i; while (in >> i) { std::cout << i; } } } 
  • so what int_type mean? - bob
  • cplusplus.com/reference/string/char_traits Integer type that can store character code. Depends on the _CharT parameter of the template<typename _CharT, typename _Traits> std::basic_ifstream In the case of std::ifstream _charT == char and int_type == int . - user194374
  • It turns out to consider the non-character type only using >> ? - bob
  • @bob We can assume that yes. - user194374
  • Clear, thanks for the reply - bob

in.get() is an analogue of getchar() - reads individual characters (char) from the stream. The method returns an int_type instead of char_type so that it can also return the end-of-file indicator (eof).

To copy numbers into a vector from a text file, you can use istream_iterator :

 #include <algorithm> // copy #include <iostream> #include <iterator> #include <vector> int main() { std::istream_iterator<int> numbers(std::cin), eof; // копируем по одному числу из ввода в вывод // std::copy(numbers, eof, std::ostream_iterator<int>(std::cout, "\n")); // или в вектор можно сохранить для дальнейшей обработки std::vector<int> a(numbers, eof); std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, "\n")); } 

istream_iterator<int>(in) uses the in >> i analog inside. Read more: How to find a word?