C++编程基础一 12-字符串

 1 // 12-字符串.cpp: 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <climits>
 7 using namespace std;
 8 
 9 int main()
10 {
11     //C语言的写法:
12      //错误的写法:没有'\0',在C语言中字符串是存在字符数组中的,'\0'则代表数组的结尾。
13     char website[] = { 'H','e', 'l', 'l', 'o', ' ', 'W', 'o', 'r','l','d', '!', };
14     //正确的写法:'\0'占了数组的一个位置,当被用做字符串输出时,字符串的长度不包括'\0',当被用做数组时,算上'\0'的长度。
15     char website2[] = { 'H','e', 'l', 'l', 'o', ' ', 'W', 'o', 'r','l','d', '!','\0' };
16     //也可以这么写:
17     char website3[] = "Hello World!";
18     //判断字符串的长度:长度为12,没有包括'\0'。
19     cout << strlen(website2) << endl; 
20     //判断数组的长度:长度为13,包含了'\0'的长度。
21     cout<<sizeof(website2) << endl;
22     cout << website2 << endl;
23     cout << website3 << endl;
24 
25     //字符串过长的问题:
26     char str[] = "sdasdsadasdasdasdsaddsadasdasda"
27         "2433359459423431413413";//中间无需添加任何符号
28     cout << str << endl;
29 
30     char name[30];
31     char food[40];
32     cout << "你的名字是:";
33     //使用cin来接收输入的时候是用空白(空格、回车 、制表符)来区分的,
34     //如果名字中有空格,就会出错。解决办法就是用cin.getline()来读取一行。
35     //cin >> name;  
36     cin.getline(name,20);
37     cout << "你喜欢的食物是:";
38     cin >> food;
39     cout << name << "喜欢吃" << food;
40 
41 
42     int t;
43     cin >> t;
44     return 0;
45 }

 

posted on 2018-07-21 14:13  uimodel  阅读(137)  评论(0编辑  收藏  举报

导航