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

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

本文关键字:一行 读取 使用 std getline      更新时间:2023-10-16

我的目标是提示用户输入消息/句子,然后使用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] != ''; ++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 ***nn";  // 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] != ''; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
}

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

如果这太复杂了,可以简单地使用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:正如@fredRalson所评论的,如果在第一个示例中将chat更改为char,它应该会起作用。然而,该代码与C.有很多共同点