使用std :: getline()读取一行?

问题描述 投票:1回答:1

我的目标是提示用户输入消息/句子,然后使用getline()将其打印在屏幕上。以下是我尝试过的两种不同尝试。

第一次尝试:

#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){

    chat message[80];
    cout << "\n what is your message today?" << endl;

    cin.getline( message, 80); // Enter a line with a max of 79 characters.
  if( strlen( message) > 0)  // If string length is longer than 0.
    {

      for( int i=0; message[i] != '\0'; ++i)
          cout << message[i] << ' ';
      cout << endl;

   }
 }

第二次尝试:

#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){

    string a = "a string";
    cout << "\n what is your message today?" << endl;
    while(getline(cin,a))
        cout << a;
    cout<<endl

   }
 }

为了第一手尝试,代码只是打印出“今天您的信息是什么?”然后退出我根本没有机会输入任何字符串。对于第二次尝试,它一直要求我输入消息。每次,当我用“ \ n”输入内容时,它将在屏幕上显示我输入的内容。我使用Control + C中断正在运行的进程以使其停止。

EDIT:为澄清和解释,我从更长的代码中提取了第一次尝试,如下所示。

#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;

char header[] = "\n *** C Strings ***\n\n";  // define a c string 
int main()
{
  char hello[30] = "Hello ", name[20], message[80];  // define a c string hello, declare two other c strings name and message
  string a="fivelength";
  cout << header << "Your first name: ";
  cin >> setw(20) >> name;      // Enter a word.


  strcat( hello, name);      // Append the name.
  cout << hello << endl;
  cin.sync();                // No previous input.
  cout << "\nWhat is the message for today?"
       << endl;

  cin.getline( message, 80); // Enter a line with a max of 79 characters.
  if( strlen( message) > 0)  // If string length is longer than 0.
    {

      for( int i=0; message[i] != '\0'; ++i)
          cout << message[i] << ' ';
      cout << endl;

   }
return 0;
}

对于以上代码,它没有给我机会在屏幕上输入消息。我将其作为另一个问题。

c++ string iostream getline
1个回答
6
投票

您将其复杂化了,您可以简单地使用std::string(它是事实上的C ++字符串)并调用该方法,而无需使用循环。

您不需要循环,因为您not

© www.soinside.com 2019 - 2024. All rights reserved.