无法使用 istringstream 从 .txt 文件中读取
can't read from .txt file using istringstream
我正在尝试编写一个相当基本的程序,它使用 istringstream 读取 .txt 文件,但出于某种原因,这段代码:
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;
}
只打印:
test.txt
我要读取的文件是一个名为 test.txt 的 .txt 文件,由 windows 编辑器创建,包含:
测试 1
测试 2
测试 3
我正在编译 Visual Studio 2017.
假设您的目标是读取文件中的每个条目,那么您使用的是错误的 class。要从文件中读取,您需要 std::ifstream
,并按如下方式使用它:
#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;
}
输出:
<newline>
test1
test2
test3
std::stringstream
用于解析字符串,不是文件。
我正在尝试编写一个相当基本的程序,它使用 istringstream 读取 .txt 文件,但出于某种原因,这段代码:
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;
}
只打印:
test.txt
我要读取的文件是一个名为 test.txt 的 .txt 文件,由 windows 编辑器创建,包含:
测试 1
测试 2
测试 3
我正在编译 Visual Studio 2017.
假设您的目标是读取文件中的每个条目,那么您使用的是错误的 class。要从文件中读取,您需要 std::ifstream
,并按如下方式使用它:
#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;
}
输出:
<newline>
test1
test2
test3
std::stringstream
用于解析字符串,不是文件。