【问题标题】:Within for-loop, Input file not reading new values into variables在 for 循环中,输入文件未将新值读入变量
【发布时间】:2018-12-04 09:48:54
【问题描述】:

我目前在 for 循环将新值读入变量时遇到问题。它对顶点、边和起始变量非常有效,但它仅对 from_、to_、weight_ 和 dir 变量第一次有效。此后每次 for 循环迭代时,它仍然使用第二行(0 1 4 false)。我很惭愧不得不为如此微薄的东西发帖,但我一生都无法弄清楚发生了什么。我已经包含了输入文件以及实现文件中使用的函数,它使用了结构体的对象 Edge,该结构体被放入向量中的列表对象中。请让我知道我是否应该发布更多内容,尽管我认为问题只是与我使用文件 I/o 的方式有关。

#include "graph.h" 
#include <iostream> 
#include <string> 
#include <vector> 
#include <list> 
#include <limits> 
#include <fstream> 

int main() 
{ 
    std::ifstream infile; 
    infile.open("graph.txt"); 
    int vertices, edges, start; 
    infile >> vertices >> edges >> start; 
    Graph graph(vertices); 
    int from_, to_; 
    double weight_; 
    bool dir; 
    std::cout << "Constructing graph" << std::endl; 
    int i = edges; 
    for (int i=0;i<edges;i++) 
    { 
        infile >> from_ >> to_ >> weight_ >> dir; 
        graph.addEdge(from_, to_, weight_, dir); 
    } 


    infile.close(); 
    return 0; 
}

输入文件(graph.txt):

6 8 2 
0 1 4 false 
0 2 7.5 false 
1 3 2 false 
1 4 5 false 
2 3 3.1 false 
2 5 6.9 false 
3 4 1 false 
4 5 3 false

实现文件中的函数:

void Graph::addEdge(int from, int to, double weight, bool isDir) 
{ 
    std::cout<< "Representing edge " << from << "," << to << " weight " 
            << weight << std::endl; 
    Edge e1(from,to,weight); 
    if (adjacent.size() < std::max(from, to) + 1) 
        adjacent.resize(std::max(from,to) +1); 
    adjacent[from].push_back(e1); 
    std::cout << "Edge added" <<std::endl; 
    if (isDir == false) 
    { 
        Edge e2(to,from,weight); 
        adjacent[to].push_back(e2); 
    } 
}

【问题讨论】:

    标签: c++ file-io


    【解决方案1】:

    你不能使用 falsetrue 这样的布尔值。它没有字符串表示,因此尝试将布尔值解析为字符串失败。

    用途:

    std::string dir;
    

    然后:

    graph.addEdge(from_, to_, weight_, dir != "false"); 
    

    【讨论】:

      【解决方案2】:

      读取bool 通常期望找到10
      (如果您检查了读取是否成功,您会注意到它没有。)

      您可以使用std::boolalpha I/O 操纵器使流查找字符序列truefalse

      示例(也适用于输出流):

      #include <iomanip>
      #include <iostream>
      #include <sstream>
      
      int main() {
          std::istringstream in("true false");
          bool value = false;
          in >> std::boolalpha;
          while (in >> value)
          {
              std::cout << std::boolalpha << value << "\n";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        • 2013-05-15
        • 1970-01-01
        • 2020-09-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多