无法使用istringstream从.txt文件中读取

时间:2018-02-03 15:21:50

标签: c++ getline 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编辑器创建,包含: test1的
TEST2
TEST3
我正在使用Visual Studio 2017进行编译。

1 个答案:

答案 0 :(得分:2)

假设您的目标是阅读文件中的每个条目,那么您使用的是错误的类。要从文件中读取,您需要documentation,并按如下方式使用它:

#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::ifstream

Live Example用于解析字符串,而不是文件。

相关问题