VS2010 C++ 学习笔记(三) 类和对象 访问限定符 String



对象实例化




从堆中申请的内存,记得释放。

*************************************************************



***************************************************************************

#include <stdlib.h>
#include <iostream>
using namespace std;

class Coordinate
{
public:
	int x;
	int y;
	void printX()
	{
		cout << x << endl;
	}
	void printY()
	{
		cout << y << endl;
	}
};
int main(void)
{      	
	Coordinate coor; //栈申请
	coor.x = 10;
	coor.y = 20;
	coor.printX();
	coor.printY();

	Coordinate *p = new Coordinate();//堆申请
	if(NULL == p)
	{
		cout << "new error" << endl;
		return 0;
	}
	p->x = 15;
	p->y = 25;
	p->printX();
	p->printY();
	delete p;
	p = NULL;
	system("pause");
	return 0;
}


**************************************************************

String





********************************************

题目:
1.提示用户输入姓名
2.接收用户输入
3.向用户问好,hello,xx
4.告诉用户长度
5.用户首字母
6.如果用户直接回车,告诉用户为空
7.如果输入的是michael,告诉是个admin


/************************************************************
/*题目:
	1.提示用户输入姓名
	2.接收用户输入
	3.向用户问好,hello,xx
	4.告诉用户长度
	5.用户首字母
	6.如果用户直接回车,告诉用户为空
	7.如果输入的是michael,告诉是个admin
****************************************************************/

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

int main(void)
{      	
	string name;
	cout << "Input you name" << endl;
	getline(cin, name); 
	if(name.empty())
	{
		cout << "input is null.." << endl;
		system("pause");
		return 0;
	}
	if (name == "michael")
	{
		cout << "You are the admin" << endl;
	}
	cout << "hello " + name << endl;
	cout << "You name length:" << name.length() << endl;
	cout << "You name first letter is:" << name[0] << endl;
	system("pause");
	return 0;
}

string IO 操作:getline

这个函数接受两个参数:一个输入流对象和一个 string 对象。getline 函数从输入流的下一行读取,并保存读取的内容到不包括换行符。和输入操作符不一样的是,getline 并不忽略行开头的换行符。只要 getline 遇到换行符,即便它是输入的第一个字符,getline 也将停止读入并返回。如果第一个字符就是换行符,则 string 参数将被置为空 string


当进行 string 对象和字符串字面值混合连接操作时,+ 操作符的左右操作数必须至少有一个是 string 类型的:

     string s1 = "hello";   // no punctuation
     string s2 = "world";
     string s3 = s1 + ", ";           // ok: adding a string and a literal
     string s4 = "hello" + ", ";      // error: no string operand
     string s5 = s1 + ", " + "world"; // ok: each + has string operand
     string s6 = "hello" + ", " + s2; // error: can't add string literals


输入为空




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值