0

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;
}
3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by alexchen
0
string input[4];

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

Edited by alexchen: n/a

0

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!

0

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.

Edited by JasonHippy: n/a

0
#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;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.