Hello, I need help with writing a quick read from a file with getchar_unlock (). There are two lines in the file that are not necessarily the same size, how many characters in each line are also not known, you need to count them in 2 arrays or vectors, thanks in advance for your help.

Problem: the code reads only 1 number, I don’t know how to do it for the whole line

#include <iostream> using namespace std; bool read_int_unlocked(int & out) { int c = getchar_unlocked(); int x = 0; int neg = 0; for (; !('0'<=c && c<='9') && c != '-'; c = getchar_unlocked()) { if (c == EOF) return false; } if (c == '-') { neg = 1; c = getchar_unlocked(); } if (c == EOF) return false; for (; '0' <= c && c <= '9' ; c = getchar_unlocked()) { x = x*10 + c - '0'; } out = neg ? -x : x; return true; } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int number; while(read_int_unlocked(number)) std::cout << number << " "; return 0; } 
  • one
    Look at the instructions on how to ask questions (a link to it is on the form for editing questions) - Alexander Muksimov
  • one
    Show your decision, and describe what exactly you are failing. ru.stackoverflow.com/help/on-topic - wirtwelt
  • Your pros, it hurts like si - test123

1 answer 1

 #include <iostream> #include <vector> int read_int_unlocked(int & out) { int c = getchar_unlocked(); int x = 0; int neg = 0; for (; !('0'<=c && c<='9') && c != '-'; c = getchar_unlocked()) { if (c == EOF) return 0; } if (c == '-') { neg = 1; c = getchar_unlocked(); } if (c == EOF) return 0; for (; '0' <= c && c <= '9' ; c = getchar_unlocked()) { x = x*10 + c - '0'; } out = neg ? -x : x; if(c == '\n') return 2; return 1; } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); std::vector<int> v1; std::vector<int> v2; int number; int oldVec = 1; bool cycle = true; while(cycle){ int res = read_int_unlocked(number); if(res == 0) cycle = false; if(res == 1) { if(oldVec) v1.push_back(number); else v2.push_back(number); } if(res == 2) { if(oldVec) v1.push_back(number); else v2.push_back(number); oldVec = false; } } for(int i = 0; i < v1.size(); i++) std::cout << v1[i] << " "; std::cout << std::endl; for(int i = 0; i < v2.size(); i++) std::cout << v2[i] << " "; std::cout << std::endl; return 0; }