Hello everyone,
my question is about an anomaly I encountered while working on an exercise from Stroustrup's book "The C++ Programming Language". The exercise is to write a program that reads file names from cin and prints the file's content with cout.
I actually got the program to work but I encountered some weird "feature" that I don't understand.
First of all, here is my code (I use a Ubuntu 12.04 laptop and g++ as a compiler):
#include<iostream>
#include<fstream>
#include<string>
std::string cat();
int main()
{
std::string data;
data = cat();
std::cout << data;
}
//Opens all files in the input line (separated by whitespaces) and gives back the contents.
std::string cat()
{
std::string files;
std::string data;
std::string buffer;
std::ifstream stream;
std::cout << "Enter file names: ";
getline(std::cin, files);
while(files.size() != 0)
{
std::string currentfile;
currentfile = files.substr(0, files.find(" "));
std::cout << "Reading: " << currentfile << "\n";
char currentf[currentfile.size()];
for(int i=0; i<currentfile.size(); i++)
{
currentf[i] = currentfile[i];
}
stream.open(currentf);
while(stream.good())
{
getline(stream, buffer);
data += buffer;
data += "\n";
}
stream.close();
if(files.find(" ") != std::string::npos)
files = files.substr( files.find(" ")+1, files.size() - files.find(" ") - 1);
else
files = "";
}
return data;
} |
Now the weird part happens in the line where I print out the "Reading: [filename]" line. If I remove that line the program does not work anymore (it compiles and reads the filename, but does not print out the files content). If I replace this line by std::cout << "\n"; , it works again.
Can anybody explain to me, why this happens? I just don't see the connection between the problem and the solution (that is, inserting this line).
I feel kind of stupid because I solved my problem but I just don't understand how I did it...
Also I guess my code is not really good, because I don't have very much experience programming. Sorry for that, every advice on how to improve the code is very much appreciated!
Thank you for your help!
Jona