This one seems really simple but for some reason I'm not getting it! Here's the problem:

USING A FOR LOOP, read 4 lines of input from the user and display it on the screen.

I made my code, which works, but it only reads the first line the user has inputted. It displays only that line 4 times instead of the 4 different lines.

Thanks!

#include <iostream>
#include <string>
using namespace std;
int main ()
{

string input;

getline (cin,input);

for (int x = 1; x <= 4; x++)
{
cout << input << endl;
}
return 0;
}

Recommended Answers

All 4 Replies

string input[4];

for(int x=1;x<4;x++){
getline(cin,input[x]);
cout<<input[x]<<endl;

Is using an array the only way to do this problem? I didn't think we were permitted to use arrays on this one. But if that's the only way to solve it, then we must be.
Thanks!

In C++ there's more than one way to skin a cat. That isn't the only way of solving this problem. If you aren't supposed to be using arrays, you could try using two strings.

e.g. One to temporarily store user input and another to build the final output string.

So each time through your loop you get a line of input from the user, bung a newline ("\n") on the end and then append that to your output string.
Something like this:

output += string(input + "\n");

After the loop you then display the output string which you built during the loop. And not an array in sight! I'm not going to spoonfeed you all of the code though, I'll leave it to you to work it out. I think I've said enough! heh heh...

Hope that is of some help to you!
Cheers for now,
Jas.

#include <string>

using namespace std;

void line(char*Filename,int maxline){

	ifstream file;
	file.open(Filename);

	string input,output;


	for(int x = 0; x < maxline; x++) 
	{
	getline(file,input);
	
	output += string(input + "\n");

	}
	cout<<output<<endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.