探讨数组与字符串输入的问题(C++版)

2020-01-06 13:37:38于海丽

本文对C++数组与字符串输入的问题进行了探讨,需要的朋友可以参考下

对于字符串问题,原来理解的不够深刻,现在讨论一些关于字符串输入的问题

探讨数组与字符串输入的问题(C++版)

1.strlen() 返回的是数组中的字符串的长度,而不是数组本身的长度。

2.strlen()只计算可见的字符,而不把空字符计算在内。

那么更有意思的在后面:

 

 
  1. char name[16] = "abcdefg";  //输出结果是多少? 
  2. cout << name << endl;  name[3] = ''; 
  3. //输出结果又是多少?  cout << name << endl;  

大家猜猜 ?

 

 
  1. # include <iostream>  # include <cstring> 
  2. # define SIZE 15  using namespace std; 
  3. int main(void)  { 
  4. char name_cin[SIZE];  char name[SIZE] = "C++owboy"; //initialized array 
  5. cout << "Hello I'm " << name;  cout << "! What is your name ? "; 
  6. cin >> name_cin;  cout << "Well " << name_cin << ", your name has "; 
  7. cout << strlen(name_cin) << " letters and is stored " << endl;  cout << "in an array of " << sizeof(name_cin) << "bytes." << endl;