Task: The INPUT.TXT text file contains integers separated by a space, possibly in several lines. For a single file view, create a list of these numbers. Remove from the list the first negative element, if any. The resulting list is recorded in the text file OUTPUT.TXT. The first part of the text file INPUT.TXT recorded integers separated by a space, perhaps in several lines. For a single file viewer, to form a list of these numbers, I understand how to do it. But how then to use the characters from the string as numbers to find the negative I can not understand. As soon as I did not try (Tell me, please) Here is the part of the code that I have already done:

#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main() { char chisla[50]; int mas[50]; ifstream file("INPUT.txt"); if (!file.is_open()) cout << "error" << endl; else { while (!file.eof()) { file.getline(chisla, 50); for (int i = 0; i < 50; i++) { while (chisla[i]) { mas[i] = mas[i] + (int)(chisla[i] - '0'); i++; } } cout << mas << endl; ofstream file_1("output.txt"); file_1 << chisla << endl; file_1.close(); } file.close(); } } 

And there are a number of restrictions: It is forbidden to use the string data type, but you can use string functions: strcmp, strcpy, strlen, etc. Those. banned only independent data type string. You need to use char *, organize reading from a file by reading the entire line using the getline function

  • You don’t need to work with strings at all. You can read numbers from a file using operator >>, and then write these numbers to the output file with the exception of the first negative number. - Vlad from Moscow

1 answer 1

Why just if you can be difficult ...

 vector<int> v; int i; . . . while(file >> i) { v.push_back(i); } 

If the out file is open for writing:

 bool wasNeg = false; int i; while(file >> i) { if (!wasNeg && i < 0) { wasNeg = true; continue; } out << i << " "; } 

And more ... Do not do this:

 while (!file.eof()) 

This check will work only after unsuccessful reading. Better this way:

 while(file.getline(...))