29
2020
04

c++快速入门

为了学习QT,所以跑去入门一下c++

第一个程序:cout

#include <iostream> 

using namespace std;//名字空间,就是c++标准库所使用的所有标识符(既类,函数,对象等的名称)都是在同一个特殊的名字空间(std)中来定义 

int addArray(int *array , int n);

int main(){
    int date[]={0,1,2,3,4,5,6,7,8,9};
    int size=sizeof(date)/sizeof(date[0]);
    cout<<"结果是"<<addArray(date,size)<<endl;//cout是输出流对象 
    return 0; 
}

int addArray(int *array,int n){
    int sum=0;
    int i;
    for(i=0;i<n;i++){
        sum+=*array++;
    }
    return sum;
}

2-cin

#include <iostream> 

using namespace std;//名字空间,就是c++标准库所使用的所有标识符(既类,函数,对象等的名称)都是在同一个特殊的名字空间(std)中来定义 

int main(){
    int sum=0;
    cout<<"请输入一串整数和任意数目的空间:" ;
    int i;//c++允许我们在程序的任意位置声明变量,所以我们就可以在实际需要使用变量的时候才来声明他们
//*当用户点击键盘上的enter键时,操作系统把键盘缓冲区的内容传输到cin流的内部缓冲区,“>>”操作符随后从这个缓冲区提取需要的信息    
 //>>它就用于从输入流对象提取信息  
  
    while(cin>>i){
        sum+=i;
        while(cin.peek()==' '){
            cin.get();
        }
        if(cin.peek()=='\n'){
            break;
        }
    }
    cout<<"结果是"<<sum<<endl;
    return 0;
}

3-cin.width()和cout.width()运用

#include "stdafx.h"  
#include <iostream>
using namespace std;
int main()
{
	int width = 4;
	char str[20];
	cout << "请输入一段文本:\n";
	cin.width(5);
	while (cin >> str)
	{
		cout.width(width++);
		cout << str << endl;
		cin.width(5);
	}
	system("pause");
	return 0;
}

cout.width(4)就是输出的字符串宽度为4,不足的会用空格补足。比方说你要输出“12”,但是在输出之前用了这句话就会输出“ 12”。cin.width(5);cin>>str;实际只能提取4个字符,str最后一个是空字符,

4-

#include <fstream> 
#include <iostream>

using namespace std;

int main(){
	ofstream out;//ofstream是写入文件,ifstream是读取文件
	  out.open("test.txt");//或者直接和上一句合并不要open既ofstream out("test.txt");
	  if(!out){
	  	cerr<<"打开文件失败"<<endl;
	  	return 0;
	  } 
for(int i=0;i<10;i++){
	out<<i;
}	

out<<endl;
out.close();
return 0;
}

c++几种打开文件模式

ios::in--打开一个可读取文件

ios::out--打开一个可写文件

ios::binary--以二进制的形式打开一个文件

ios::app--写入的所有数据将被追加到文件的末尾

ios::trunk--删除文件原来已存在的内容

ios::nocreate--如果要打开的文件并不存在,那么以此参数调用open函数将无法进行(意思就是说这个文件必须存在,不能新创建)

ios::noreplece--如果要打开的文件已存在,试图用open函数打开时将返回一个错误

#include <fstream> 
#include <iostream>

using namespace std;

int main(){
	ofstream out("test.txt",ios::app);//ofstream是写入文件,ifstream是读取文件
	 // out.open("test.txt");
	  if(!out){
	  	cerr<<"打开文件失败"<<endl;
	  	return 0;
	  } 
for(int i=3;i<10;i++){
	out<<i;
}	

out<<endl;
out.close();
return 0;
}

可读可写在一个程序里面

#include <fstream> 
#include <iostream>

using namespace std;
int main(){
fstream fp("test.txt",ios::in|ios::out);
if(!fp){
cerr<<"打开文件失败!"<<endl;
return 0;
}
fp<<"wwwwwdedede";
static char str[10];
fp.seekg(ios::beg);
fp.close();
return 0;
}


微信扫码关注

更新实时通知

« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。