Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

C++ Tutorial

Installing C++ compiler

Windows-

 How to install MinGW C/C++ Compiler on Windows 11 - GCC G++ Installation Tutorial

Mac-

Preferred installation:

Most MacOS already has g++ installed. If not, you can download the latest version of XCode.

https://developer.apple.com/xcode/

Alternative installation:

 Install GCC/G++ on MacOS arm64 M1 Mac

Compiling sample C++ code

To Compile:

g++ -std=c++11 main.cpp

To Run:

macOs-

./a.out

windows- (replace ./a.out with ./a)

./a

Hello World

Sample main.cpp

#include <iostream>

using namespace std;

int main(int argc, const char* argv[]) {

cout << "Hello World ~ CSCI 323" << endl;

return 0;

}

Compile and run:

g++ -std=c++11 main.cpp && ./a.out

Expected:

Hello World ~ CSCI 323

Arrays

int intData[100];

Dynamically declare a 1-D integer array of size N (let the array be named intData)

int* intData = new int[N];

Dynamically declare a 2-D integer array of size Rows by Cols. (let the array be named 

intData).

int**  intData = new int*[Rows];

for (int i = 0; i< Rows; i++)

intData[i] = new int[Cols];

Reading a file

sample.txt

323 c++ project tutorial

sample text

file

main.cpp

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main(int argc, const char* argv[]) {

ifstream myFile;

myFile.open(argv[1]);

if (!myFile.is_open()) {

cout << "Unable to open file" << endl;

exit(1);

}

string word;

while (myFile >> word) {

cout << "Word: " << word << endl;

}

return 0;

}

Compile and run:

g++ -std=c++11 main.cpp && ./a.out sample.txt

Expected:

Word: 323

Word: c++

Word: project

Word: tutorial

Word: sample

Word: text

Word: file

Writing to a file

input.txt

Emily 21

Ben 23

Jake 29

Ashley 25

Mark 17

main.cpp

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main(int argc, const char* argv[]) {

ifstream inputFile(argv[1]);

if (!inputFile.is_open()) {

cout << "Unable to open file" << endl;

exit(1);

}

ofstream outputFile(argv[2]);

string name;

int age;

while (inputFile >> name >> age) {

outputFile << name << " is " << age << " years old" << endl;

}

return 0;

}

Compile and run:

g++ -std=c++11 main.cpp && ./a.out input.txt output.txt

output.txt: Note: Automatically generated by your code

Emily is 21 years old

Ben is 23 years old

Jake is 29 years old

Ashley is 25 years old

Mark is 17 years old