前情提要: 本人从事数据处理的工作大约四年之久,主要的语言为R、SQL and Python,身为数据程式人这几年这么竞争,不时还是会上线上课程,近来的课程刚好有C++的需求,注册一门课程直接上下去。
以下是课程的笔记,本人非程式本科出身主要会使用我写别程式语言的逻辑来说明。
一、基本格式
1.include就像是 R 里面的library 、python 里面的 import ,iostream就是套件了。
2.有一个要注意的 带入套件的时候 可以使用 <套件> 和 "套件",<>会直接去抓标準套件,而""会先抓你本地端的套件。
3.int main 就是主要的写法去执行程式,里面就是输入要执行的内容,cout就c out 的意思打印出后面的文字"Hello world, I am ready for C++"。
#include <iostream> int main() { std::cout << "Hello world, I am ready for C++"; return 0; }
二、文字注解
总共有两种
1.单行 // 只能一行
2.多行 /* 好几行
第二行*/
三、using namespace
主要就是在指定一些功能的时候要选择要使用的模块类似 std::cout 中 前面的 std,但是如果你前面加了using namespace std; 代表之后的程式码只要打count,前面不需要再加std::。
老师解说他有时会这样使用有时候不会,有时候你的project太大可能很複杂就比较不会用using namespace 的方式,因地制宜。
四、变数
1.const 不能修改
前面如果加了const不能后面再写入其他的值。
const int weightGoal = 100;
weightGoal = 200;
2.输出
可以使用文字加上变数输出,A为变数。
PS \n 换行
\t 按下一次tab键一样功能
cout<<"int size = "<< A <<"\n";
五、IO(输入、输出)
使用 fstream library
这里他只有稍微简单介绍一下,大概就是ifstream(in)和ofstream(out)的两种功能。
#include <iostream>#include <fstream>#include <string>using namespace std;int main () { string line; //create an output stream to write to the file //append the new lines to the end of the file ofstream myfileI ("input.txt", ios::app); if (myfileI.is_open()) { myfileI << "\nI am adding a line.\n"; myfileI << "I am adding another line.\n"; myfileI.close(); } else cout << "Unable to open file for writing"; //create an input stream to read the file ifstream myfileO ("input.txt"); //During the creation of ifstream, the file is opened. //So we do not have explicitly open the file. if (myfileO.is_open()) { while ( getline (myfileO,line) ) { cout << line << '\n'; } myfileO.close(); } else cout << "Unable to open file for reading"; return 0;}
六、Header Files
把一些设定放在Header Files里面,再把他include进来,
例如 #include ""main.hpp"
七、cin和input.txt
可以使用cin和input.txt来作为参数的输入
PS 其中cin 中间不能有空白,有空白就要使用getline。
/*This program accepts inputs from the input.txt file*/ #include <iostream>#include <string>int main(){ std::string userName; std::cout<<"Tell me your nickname?: "; std::getline(std::cin, userName); std::cout<<"Hello "<<userName<<"\n"; return 0;}
八、资料格式转换
使用sstream,然后用stringstream转成inches
#include
std::getline (std::cin,stringLength);
std::stringstream(stringLength) >> inches;
std::cout<<"You entered "<<inches<<"\n";
九、最后介绍了资料格式
main.cpp - the main program
main.hpp - the header file
mainFunctions.cpp - a file for any functions
input.txt - for user inputs. Delete the first line of the file,
otherwise the line will be seen as an input.