【问题标题】:Can anyone explain this program in detail谁能详细解释一下这个程序
【发布时间】:2021-02-26 11:41:54
【问题描述】:
#include <iostream>
using namespace std;

int main()
{
   const int SIZE=4;
   char Sentence[SIZE];
   char Sentence2[SIZE];

   cout << "Enter the sentence" <<endl;
   cin >> Sentence;

   cout << "\nThe string read with cin was"
 << endl <<Sentence <<endl;
  char ch = cin.get();

  cout << "Enter the second sentence: "<<endl;
  cin.get(Sentence2,SIZE,'$');
  cout << Sentence2 <<endl;
}

输出


Enter the sentence
This is my first sentence

The string read with cin was
This
Enter the second sentence:
is

我刚开始学习 C++,我无法理解这个程序以及它的输出。请任何人建议我从哪里学习或详细解释它。

【问题讨论】:

  • 哪一部分不明白?
  • char 大小为 4 的数组只能容纳 3 个字符,为空终止符留出空间。
  • 这部分的输出我看不懂:cout
  • 是的,你能解释一下吗
  • 这并没有解决问题,但那是写得很糟糕的代码,所以你不需要花太多时间去理解它。

标签: c++ get stream cin


【解决方案1】:
cout << "Enter the second sentence: "<<endl;

Enter the second sentence: 打印到控制台。

cin.get(Sentence2,SIZE,'$');

最多可读取SIZE - 1 字符数,或直到第一个$ 字符从控制台到Sentence2 数组(包括空格字符。为零终止符保留1 个字符)。

cout << Sentence2 <<endl;

Sentence2 变量打印到控制台。

【讨论】:

  • 我无法理解,这里我们没有输入任何 Sentence2,所以它是如何工作的。你明白我的意思吗
  • @AshKetch 输入就像一个管道。您输入“这是我的第一句话”,它会一直保留在那里,直到它被完全提取。首先cin &gt;&gt; Sentence; 只读取第一个单词,但其余的都留在那里。当您执行cin.get 时,它会继续从管道中读取其余字符。
  • 哦,好的,我明白了。谢谢你的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
相关资源
最近更新 更多