Reputation: 79
I'm trying to write a fairly basic program, that reads a .txt file using istringstream, but for some reason this code:
int main(int argc,char* argv[])
{
std::string filename = "test.txt";
std::stringstream file(filename);
while (std::getline(file, filename))
{
std::cout << "\n" << filename;
}
return 0;
}
only prints:
test.txt
The file i'm trying to read is a .txt file named test.txt created by windows editor containg:
test1
test2
test3
I'm compiling with Visual Studio 2017.
Upvotes: 0
Views: 961
Reputation: 11769
Assuming your goal was to read each of the entries in the file, you are using the wrong class. For reading from files, you need std::ifstream
, and would use it as follows:
#include <iostream>
#include <fstream>
#include <string>
int main(int argc,char* argv[])
{
std::string filename = "test.txt";
std::ifstream file(filename);
if (file.is_open())
{
std::string line;
while (getline(file, line))
{
std::cout << "\n" << line;
}
}
else
{
// Handling for file not able to be opened
}
return 0;
}
OUTPUT:
<newline>
test1
test2
test3
std::stringstream
is used for parsing strings, not files.
Upvotes: 3