why is '0' value being skipped in this code?

I am in my first few weeks of learning c++

I have a program that is supposed to read in integers and output asterisks.
I have the program working fine except that if zero is inputted that line is removed.

I want the program to still input the zero value by skipping a line in the text, but it just eliminates the line all together. Will someone please help me understand this?

here is the portion of code that writes the asterisks to a file as they are inputted and then outputs the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cin>>number;
if(number==0){myfile<<" \n";}
while(number>0){number--;myfile<<"*";}

myfile<<endl;
times--;line++;}
myfile.close();

//read the file and print it
ifstream inputfile("asterisks.txt");
char buffer[128];
while (inputfile >> buffer)
{
cout<<buffer<<endl;
}
inputfile.close();



Use
1
2
3
4
5
6
7
8
   //read the file and print it
   ifstream inputfile("asterisks.txt");
   char buffer[128];
   while (inputfile.getline(buffer,128) )
   {
      cout<<buffer<<endl;
   }
   inputfile.close();

The >> operator is skipping over the empty lines in the file.
1
2
3
if(number==0){myfile<<" \n";} // writes a space to myfile
// ...
while (inputfile >> buffer) // white spaces are skipped on input 


This creates a buffer overflow vulnerability in you code.
1
2
char buffer[128];
while (inputfile >> buffer)
See: https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/295-BSI.html

Using std::string along with std::getline() would solve both the problems in one shot. See: http://www.cplusplus.com/reference/string/getline/


Thanks, crystal clear now.
I'm still doing it wrong.

I guess I need more work on std:getline()

I tried this but I only got the last line out.

1
2
3
4
5
6
string str;
ifstream inputfile("asterisks.txt");

getline (inputfile,str);

cout << str << "\n";
std::getline() gets one line.

To get every line in the input stream, you must have a loop, reading one line during each iteration, till there are no more lines to be read.

while( std::getline ( inputfile, str ) ) std::cout << str << "\n" ;
perfect thanks guys
Topic archived. No new replies allowed.