- (10%) Determine
whether the syntax of the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
/* Return a value vs. Return a reference */
#include <iostream>
using std::ostream;
class CInt {
friend ostream& operator<<(ostream& output, const CInt& b);
public:
CInt(int n=0): value(n) {}
CInt Inc() { ++value; return *this; }
private:
int value;
};
ostream& operator<<(ostream& output, const CInt& b) {
output << b.value;
return output;
}
int main()
{
int a = 0;
CInt b(0);
/* Function Chaining
- https://cplusplus.com/forum/general/143639/ */
std::cout << ++++a << ' ' << b.Inc().Inc() << std::endl;
std::cout << a
<< ' ' <<
b
<< std::endl;
return 0;
}
- (10%) Determine
whether the syntax of the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
/* c_str() */
#include <iostream>
#include <string>
int main()
{
std::string city("King");
char ptr1[5] = { 0 };
city.copy(ptr1, city.length());
const char* ptr2 = city.c_str();
city = "Land";
std::cout << city << std::endl;
std::cout << ptr1 << std::endl;
std::cout << ptr2 << std::endl;
return 0;
}
- (10%)
Determine
whether the syntax of the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
/* I/O Stream, File Stream, String Stream */
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#define N 5
int main()
{
std::ofstream outfile("a.txt");
for (int i=1; i<=N; ++i)
for (int j=1; j<=i; ++j)
outfile << j << (j==i?'\n':' ');
outfile.close();
int n;
std::string line;
std::ifstream infile("a.txt");
while (getline(infile, line)) {
std::cout << line.length() << '\t';
int sum = 0;
std::istringstream iss(line);
while (iss >> n)
sum += n;
std::cout << sum << std::endl;
}
infile.close();
return 0;
}