我的目标是提示用户输入消息/句子,然后使用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;
}
对于以上代码,它使我没有机会在屏幕上输入消息。我将其作为另一个问题。
答案 0 :(得分:6)
这使您过于复杂,您可以简单地使用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所说,如果在第一个示例中将chat
更改为char
,它应该可以工作。但是,该代码与C有很多共同点。