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

Using std::getline() to read a single line?

提问人:kkxx 提问时间:11/1/2019 最后编辑:kkxx 更新时间:11/1/2019 访问量:1479

问:

我的目标是提示用户输入消息/句子,然后将其打印在屏幕上,使用.以下是我尝试过的两种不同的尝试。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 中断正在运行的进程以使其停止。

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

#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++ 字符串 IOSTREAM getLine

评论

1赞 Fred Larson 11/1/2019
在第二个例子中,为什么是循环?这将继续阅读,直到 EOF(对于 Windows,ctrl-d 或 ctrl-z)。while
3赞 Fred Larson 11/1/2019
如果我更改为:ideone.com/hOSUIC,您的第一个示例对我来说很好用chatchar
0赞 SurvivalMachine 11/1/2019
您应该 #include < string>而不是 <cstring>。

答:

6赞 gsamaras 11/1/2019 #1

你把它弄得太复杂了,你可以简单地使用 std::string,这是事实上的 C++ 字符串,并调用该方法,而不使用循环。

你不需要循环,因为你不会重复读行,而只想读一行,所以不需要循环。

#include <iostream>
#include <string> // not cstring, which is the C string library

using namespace std;

int main(void)
{
    string message; // it can be an empty string, no need to initialize it
    cout << "What is your message today?" << endl;
    getline(cin, message);
    cout << message;
    cout<<endl;

    return 0;
}

输出(输入:“Hello Stack Overflow!”):

What is your message today?
Message: Hello Stack Overflow!

PS:正如@fredLarson评论的那样,如果您在第一个示例中更改为,它应该可以工作。但是,该代码与 C 有很多共性。chatchar

评论

2赞 Fred Larson 11/1/2019
是的,我也更喜欢这个版本。我认为 OP 唯一的错误是将其置于循环中。std::string
0赞 gsamaras 11/1/2019
啊@FredLarson很好的观察,我看到了标题,很气馁,我更新了我的答案,谢谢。cstring