【问题标题】:Read a file line by line with specific data C++使用特定数据 C++ 逐行读取文件
【发布时间】:2018-05-08 17:49:27
【问题描述】:

我有一个格式如下的文件:

11
1 0
2 8 0
3 8 0
4 5 10 0
5 8 0
6 1 3 0
7 5 0
8 11 0
9 6 0
10 5 7 0
11 0

第一行是行数,所以我可以循环读取行数的文件。 对于其他行,我想逐行读取文件并存储数据,直到我在行上得到一个“0”,这就是为什么每行末尾都有一个 0。 第一列是任务名称。 其他列是约​​束名称。

我尝试编写一些代码,但它似乎不起作用

printf("Constraints :\n");
for (int t = 1; t <= numberofTasks; t++) 
{
    F >> currentTask;
    printf("%c\t", currentTask);
    F >> currentConstraint;
    while (currentConstraint != '0') 
    {
        printf("%c", currentConstraint);
        F >> currentConstraint;
    };
    printf("\n");
};

“0”代表任务约束的结束。

我认为我的代码不能正常工作,因为任务 4 的约束 10 也包含“0”。

提前感谢您的帮助

问候

【问题讨论】:

  • 请编辑您的问题以包含minimal reproducible example
  • “编辑您的问题以包含”是什么意思?
  • 哪个词你特别不明白?
  • 你为什么要混合流?要么坚持使用 C++ I/O (operator&gt;&gt;),要么使用 C I/O 流 (printf)。
  • 我推荐使用std::getlinestd::string 读取一行文本。您可以使用std::istringstream 从字符串中读取数字。

标签: c++ file stream


【解决方案1】:

问题是您正在从文件中读取单个字符,而不是读取整个整数,甚至是逐行读取。将 currentTaskcurrentConstraint 变量更改为 int 而不是 char,并使用 std::getline() 读取行,然后从中读取整数。

试试这个:

F >> numberofTasks;
F.ignore();

std::cout << "Constraints :" << std::endl;
for (int t = 1; t <= numberofTasks; ++t) 
{
    std::string line;
    if (!std::getline(F, line)) break;

    std::istringstream iss(line);

    iss >> currentTask;
    std::cout << currentTask << "\t";

    while ((iss >> currentConstraint) && (currentConstraint != 0))
    {
        std::cout << currentConstraint << " ";
    }

    std::cout << std::endl;
}

Live Demo

话虽如此,每一行的终止 0 是不必要的。 std::getline() 到达行尾时停止读取,operator&gt;&gt; 到达流尾时停止读取。

Live Demo

【讨论】:

  • 我明白你做了什么,你只是读到行尾,而不是读到 0。而且我们只接受不同于 0 的约束。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2014-06-21
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
相关资源
最近更新 更多