The program should get a few words (number is unknown) from the user as long as he continues entering text and then should print them down as a list.
Consider the user enters some words as:
Aang Kyoshi Shirin Farhad Parand Kamran
The output should be:
[Aang, Kyoshi, Shirin, Farhad, Parand, Kamran]
I've write down this code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string current;
int counter = 1;
while (cin >> current)
{
if (counter == 1)
cout << '[' << current << ", ";
else
cout << current << ", ";
counter = counter + 1;
}
cout << ']' << endl;
return 0;
}
And the result is as:
cout << current << ", ";
What should I do to not print the last ,
?
For line 17:
cout << ']' << endl;
How the code will exit the while loop? It doesn't exit the loop with an Enter
, Ctrl+Z
or Ctrl+D
and so the line 17 is not executed?!