Моя цель - предложить пользователю ввести сообщение / предложение, а затем распечатать его на экране, используя 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», он отображал то, что я вводил на экране. Я использую Ctrl + 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;
}
Для приведенного выше кода, это не дает мне возможность ввести сообщение на экране. Я поставлю это как другой вопрос.