brrnrr_47 brrnrr_47 - 1 month ago 7
C++ Question

Issues with getline c++

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.

Answer

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
Comments