【问题标题】:can't read from .txt file using istringstream无法使用 istringstream 从 .txt 文件中读取
【发布时间】:2018-07-13 21:54:19
【问题描述】:

我正在尝试编写一个相当基本的程序,它使用 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;
}

仅打印:
测试.txt

我要读取的文件是由 Windows 编辑器创建的名为 test.txt 的 .txt 文件,其中包含:
测试1
测试2
测试3
我正在使用 Visual Studio 2017 进行编译。

【问题讨论】:

  • 您确定要 string 流而不是像 std::ifstream 这样的文件流吗?该程序完全按照您的指示进行操作,即使用字符串 "test.txt" 创建一个字符串流,然后读取该字符串。

标签: c++ getline stringstream


【解决方案1】:

假设您的目标是读取文件中的每个条目,那么您使用了错误的类。从文件中读取,您需要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

Live Example

std::stringstream 用于解析字符串,而不是文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多