- 0. 小结
- 4. What makes C++ Different
- 7. Program Structure
- 10. Adding Comments
- 11. Style Guide
- 13. HelloWorld programe
- 16. Using Namespace
- 20. Print Variables Programming Quiz
- 22. Define Constants
- 23. Enumerated Constants 枚举常量
- 24. Format outputs
- 27. File IO
- 29. Header Files
- 30. User Input
- 35. String Input
- 38. More on Strings
0. 小结
本章介绍了C++最基础的内容,主要集中在输入输出,程序结构等方面。
4. What makes C++ Different
C++ works directly with the hardware.
C++ differs from most more modern programming languages by working directly on the hardware,and working very efficiently with the hardware.
And it provides really strong abstraction machanisms that are very powerful,very modern so that you don’t have to deal with the low level stuff all the time and you can still be efficient.
7. Program Structure
#include <iostream>
int main()
{
std::cout << "Hello world, I am ready for C++";
return 0;
}
#include <iostream>
:the preprocessor directives 预编译指令,后面的<>表示从系统目录查找,如果换成”“,如 #include "main.hpp"
则表示在当前目录查找,无法找到,再从系统目录查找。
10. Adding Comments
/* ... */
多行注释- ` // ` 单行注释
11. Style Guide
- A straightforward style guide is:Modern C++ Coding Guidelines
- For a more detailed guideline:Google C++ Style Guideline
13. HelloWorld programe
/*write a C++ program that outputs the following statement:
*** "Hello world, I am ready for C++"
*/
#include <iostream>
int main() {
std::cout << "Hello world, I am ready for C++";
return 0;
}
16. Using Namespace
using namespace std;
int main()
{
}
如上添加了using namespace std;
之后,就可以直接使用cout << "Hello world, I am ready for C++";
了。
This tells the compiler to assume we are using the standard library, so we don’t have to write std::.
表明我现在使用的就是标准库。
20. Print Variables Programming Quiz
/*GOAL: Practice writing to the console and learn
**the variables types available in C++
**Print the sizes of each variable to the console.
**Print them in the following order:
**int, short, long, char, float, double, bool
**
**Use the command sizeof(variable type) ie: sizeof(int)
*/
using namespace std;
#include <iostream>
int main(){
cout <<sizeof(int)<<endl;
cout <<sizeof(short)<<endl;
cout <<sizeof(long)<<endl;
cout <<sizeof(char)<<endl;
cout <<sizeof(float)<<endl;
cout <<sizeof(double)<<endl;
cout <<sizeof(bool)<<endl;
return 0;
}
输出
4
2
8
1
4
8
1
最后的换行也可以使用cout<<"bool size = "<<sizeof(bool)<<"\n";
22. Define Constants
使用const
可以定义常量,常量在程序运行期不能改变值,比如:
const int weightGoal = 100;
23. Enumerated Constants 枚举常量
C++ also allows for enumerated constants. This means the programmer can create a new variable type and then assign a finite number of values to it. Here is the form of the enum keyword:
enum type_name {
value1,
value2,
value3,
.
.
} object_names;
For example: enum MONTH {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
In this example the enum variable MONTH has twelve possible values. These 12 values translate into 12 integer values.
Jan = 0
Feb = 1
etc.
示例代码如下:
/*Enum example*/
#include <iostream>
using namespace std;
int main()
{
//define MONTHS as having 12 possible values
enum MONTHS {Jan, Feb, Mar, Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
//define bestMonth as a variable type MONTHS
MONTHS bestMonth;
//assign bestMonth one of the values of MONTHS
bestMonth = Jan;
//now we can check the value of bestMonths just
//like any other variable
if(bestMonth == Jan)
{
cout<<"I'm not so sure January is the best month\n";
}
cout << Dec << endl;
cout << Nov << endl;
return 0;
}
输出:
I'm not so sure January is the best month
11
10
24. Format outputs
通过#include <iomanip>
可以实现一些格式化输出
/*Enum example*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout<<"\n\nThe text without any formating\n";
cout<<"Ints"<<"Floats"<<"Doubles"<< "\n";
cout<<"\nThe text with setw(15)\n";
cout<<"Ints"<<setw(15)<<"Floats"<<setw(15)<<"Doubles"<< "\n";
cout<<"\n\nThe text with tabs\n";
cout<<"Ints\t"<<"Floats\t"<<"Doubles"<< "\n";
return 0;
}
输出为:
The text without any formating
IntsFloatsDoubles
The text with setw(15)
Ints Floats Doubles
The text with tabs
Ints Floats Doubles
27. File IO
File IO Steps:
- Include the
library - Create a stream (input, output, both)
- ofstream myfile; (for writing to a file)
- ifstream myfile; (for reading a file)
- fstream myfile; (for reading and writing a file)
- Open the file myfile.open(“filename”);
- Write or read the file
- Close the file myfile.close();
下面的示例代码,用于写入新的行到文件,并读取文件输出:
/*The goal of this quiz is to practice writing and reading files.
**Read the contents of input.txt and then write to it.
**
**We are using input.txt as our file. This is not an ideal
**situation, because when we write to it, we cannot
**see the changes. We can manually write in input.txt and
**we can also use the program to write to the file.
**Then we can read what we wrote using our program.
**
**Your assignment for this quiz**
**Change the contents of the file called input.txt
**Change the ifstream and ofstream to fstream
*/
#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 write to the file
ifstream myfileO ("input.txt");
if (myfileO.is_open())
{
while ( getline (myfileO,line) )
{
cout << line << '\n';
}
myfileO.close();
}
else cout << "Unable to open file for reading";
return 0;
}
输出如下:
Read and write to this file.
What am I doing here?
This is not a good example of a file
I am adding a line.
I am adding another line.
29. Header Files
main.hpp
#include <iostream>
#include <string>
using namespace std;
main.cpp
#include "main.hpp"
int main()
{
cout<<"Hello, I use header files!";
return 0;
}
30. User Input
/*This program accepts inputs from the input.txt file*/
#include <iostream>
#include <string>
int main()
{
int year = 0;
int age = 0;
std::string name = " ";
//print a message to the user
std::cout<<"What year is your favorite? ";
//get the user response and assign it to the variable year
std::cin >> year;
//output response to user
std::cout<<"How interesting, your favorite year is "<<year<<"!\n";
//print a message to the user
std::cout<<"At what age did you learn to ride a bike? ";
//get the user response and assign it to the variable age
std::cin >> age;
//output response to user
std::cout<<"How interesting you learned to ride at "<<age<<"!\n";
std::cout<<"What is your name? ";
std::cin>>name;
std::cout<<"Hello "<<name<<" !\n";
return 0;
}
35. String Input
- that std::cin: will not retrieve strings that have a space in them. It will see the space as the end of the input. We will obviously need a method to enter strings.
- getline:: it will retrieve characters from the std::cin source and stores them in the variable called variableName. It will retrieve all characters until **the newline or “\n” **is detected.
#include<iostream>
#include<string>
using namespace std;
int main(){
string userName;
string age;
cout << "Tell me your age:";
cin >> age;
cout << age << endl;
cout << "Tell me your full name:";
getline(cin,userName);
cout << userName << endl;
return 0;
}
下面通过terminal输入了32 35 wangling lijun
,但是32
后面有空格,所以通过cin
截取输入的时候,只截取到了32
;但是后面的35 wangling lijun
,最后通过了换行符\n
,所以getline
截取了后面的内容。
Tell me your age:32 35 wangling lijun
your age:32
Tell me your full name:your name: 35 wangling lijun
38. More on Strings
通过sstream
可以将得到的字符串转换成其他的数值类型,十分方便。
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
string age;
int ageInt;
float ageFloat;
cout << "Input your age:" << endl;
getline(cin,age);
cout << age << endl;
stringstream(age) >> ageInt;
cout << ageInt-2 << endl;
stringstream(age) >> ageFloat;
cout << ageFloat-4.0 << endl;
return 0;
}