Re: What is the output of this program?
A mistake made me stare at the screen for a while ...
Could you give some hints to avoid similar mistakes systematically?
Probably the easiest change would be to use the string's "at" function
for range-checked access, and encase your code in a try/catch block to
print an error message.
Also, you could use "vector<string>" instead of "string v1[5]". vector
also provides a at() function, but you usually have to initialize it
with a bunch of .push_back's.
Derek.
Your code would look like this. When executed, it will print a
string::at exception, indicating that you tried to access beyond the
end of a string.
=======
#include <string>
#include <iostream>
using namespace std;
string ToUpper(const string& s1)
{
string s2;
for (int i = 0; i < s1.size(); ++i)
if (isalpha(s1.at(i))) s2.at(i) = toupper(s1.at(i));
return s2;
}
int main()
{
try
{
string v1[5] = {"This", "is", "a", "small", "quizz"};
string v2[5];
for (int i = 0; i < 5; ++i)
{
v2[i] = ToUpper(v1[i]);
cout << v1[i] << " " << v2[i] << endl;
}
}
catch(exception& x)
{
cout << "EXCEPTION: " << x.what() << endl;
}
return 0;
}
=========
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]