-1

For some reason i cannot get for loop to work. It doesn't print anything. Here is code:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string concatenated;
    for (string buffer; cin >> buffer; concatenated += buffer);
    cout << "The concatenated string is " << concatenated << endl;

    return 0;
}

2 Answers2

2

The problem is that for-loop will not exit automatically. It is continually go in loop and wait for next input. That's why you are not getting any outpur at your end.

You should enter Control+Z on Windows and Control+D on Unix plateforms to enter EOF character on . See this to know more.

The code is fine. See it working here

Following is output from my local. The code used is same as posted and available here.
enter image description here

cse
  • 4,066
  • 2
  • 20
  • 37
0

You need something to stop the loop from waiting for more input.. You may use a special string to do this..

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string concatenated;
    for (string buffer; cin >> buffer && buffer!="STOP"; concatenated += buffer);
    cout << "The concatenated string is " << concatenated << endl;

    return 0;
}
Ebram Shehata
  • 446
  • 5
  • 20