Code is supposed to transform all the letters in uppercase and to print the sum of the digits.
Ex:
in:
5
a B 6 % 7
out:
AB
13
The problem is that it uses too much memory and after some tests, I realized that when I print c and S on the file it uses a large amount of memory.
How can I modify it?
#include <iostream>
#include <fstream>
#include <cctype> // for toupper(), isalpha(), isdigit()
usingnamespace std;
int main()
{
ifstream fin("alfanumeric.in");
// You should always check that the file opened
// (especially for input files)
if (!fin)
{
cout << "Cannot open input file.\n";
return 1;
}
ofstream fout("alfanumeric.out");
int n;
fin >> n;
int s = 0;
for (int i = 0; i < n; i++)
{
char c;
fin >> c; // this will automatically skip whitespace
if (isalpha(c))
fout << (char)toupper(c);
elseif (isdigit(c))
s += (int)c - '0';
}
fout << endl << s << endl;
// files opened within this scope
// are automatically closed at the end of the scope
}
EDIT: The above idea was that maybe the file didn't open and n had garbage in it, possibly a very large value. But since C++11, if extraction fails then 0 is written to the variable, so that's probably not what's happening (unless the site is using pre-C++11, which would be idiotic).
What site is it? Can you post a link to the problem?
What is n? Is s overflowing? What is the value of s? Should n, i, s be unsigned? I suspect that << is using recursion to output the digits - which could be why it's taking so much memory. If the site is checking the memory usage that carefully, you may need to write your own function to output a large number.
#include <iostream>
#include <fstream>
#include <cctype>
#include <memory>
usingnamespace std;
int main()
{
ifstream fin("alphanumeric.in");
if (!fin) {
cout << "Cannot open input file.\n";
return 1;
}
ofstream fout("alphanumeric.out");
if (!fout) {
cout << "Cannot open output file.\n";
return 2;
}
size_t n {};
fin >> n;
size_t s {};
for (size_t i = 0; i < n; ++i) {
char c {};
fin >> c;
if (isalpha(c))
fout.put((char)toupper(c));
elseif (isdigit(c))
s += (int)c - '0';
}
size_t l {};
size_t ss {s};
for (; ss > 0; ++l)
ss /= 10;
constauto out {newchar[l + 1]};
auto out1 {out + l};
*out1 = 0;
for (; s > 0; s /= 10)
*--out1 = (s % 10) + '0';
fout.put('\n');
for (out1 = out; *out1; ++out1)
fout.put(*out1);
fout.put('\n');
delete[] out;
}