-2

Wanting to do some fancy formatting. I have several lines that I want to interact with each other. Get the first two lines. Print out the character in the second line times the integer in the first line. Seperate them all with a asterisk character. No asterisk after the final character is printed. Move onto the next integer and character. Print them on a separate line. Do this for the whole list. The problem I am having is printing them on separate lines. Example:

5
!
2
?
3
#

Desired output:

!*!*!*!*!
?*?
#*#*#

My output:

!*!*!*!*!*?*?*#*#*#*

A chunk of the code. I am reading the data about the characters and numbers from a separate text file. So I am using the getline function.

Here is a chunk of the code:

ifstream File;
File.open("NumbersAndCharacters.txt")
string Number;
string Character;
while(!File.eof(){
  getline(File, Number);
  getline(File, Character);
//a few lines of stringstream action
  for (int i=0; i<=Number; i++){
      cout<<Character<<"*";}//end for. I think this is where
                            //the problem is.
  }//end while
File.close();
return 0;

Where is the error? Is it the loop? Or do I not understand getline?

It should be printing an "endl" or "\n" after each multiplication of a character is done.

I asked this question a few days ago. It did not include my code. It was put on hold. I edited the questions and flagged it for moderator review 24 hours ago. There has been no response from moderators or those who put it on hold, so I am re-asking.

brrnrr_47
  • 13
  • 5

2 Answers2

0

If the read character is the last of its line, just put "endl" instead of "*" since getLine() doesn't include the line return:

while(!File.eof(){
      getline(File, Number);
      getline(File, Character);
    //a few lines of stringstream action
      for (int i=0; i<=Number; i++){
          cout<<Character;
          if (i == Number)
              cout<<endl;
          else
               cout<<"*";
       }
    }//end while
Treycos
  • 7,373
  • 3
  • 24
  • 47
0

getline wont read in the newline at the end of the line in your file. You also don't add a newline anywhere. In case you are confused, a newline is the character '\n' and represents a newline break (on windows it is usually "\n\r", newline carriage return).

You need to add your own newline:

for (int i=0; i<=Number; i++){
  cout<<Character;
  if (i != Number) {
      cout << '*';
  }
}
cout << "\n";
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175