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

2020-01-06 13:37:38于海丽
  • cin >> dessert; //输入甜点的名字  cout << "I have some delicious " << dessert; 
  • cout << " for you, " << name << "." << endl;  return 0; 
  • 探讨数组与字符串输入的问题(C++版)

    释义:

    cin使用空白(空格、制表符、换行符)来定字符串的边界,cin在获取字符数组输入时只读取第一个单词,读取单词后,cin将该字符串放到数组中,并自动在结尾添加空字符''

    cin把Meng作为第一个字符串,并放到数组中,把Liang放到输入队列中第二次输入时,发现输入队列Liang,因为cin读取Liang,并将它放到dessert数组中

    这时如果能输入一行数据,这个问题不就解决了吗?

    getline()、get()可以实现...

     

     
    1. # include <iostream>  using namespace std; 
    2. int main(void)  { 
    3. const int ArSize = 20;  char name[ArSize]; 
    4. char dessert[ArSize];  cout << "Enter you name : " << endl; 
    5. cin.getline(name,ArSize);  cout << "Enter you favorite dessert : " << endl; 
    6. cin.getline(dessert,ArSize);  cout << "I have some delicious " << dessert; 
    7. cout << " for you," << name << endl;  return 0;