程序没有读取所需的txt文件

时间:2016-01-22 07:25:34

标签: c++ qt

所以我正在试验图表。读取txt文件并不适合某些原因。是的,我确保它是同一个名字。 我用的是什么:Qt 这是程序:

#include <iostream>
#include <sstream>
#include <fstream>
#include <set>
#include <vector>
#include <list>
#include <climits>

using namespace std;

list<pair<int, int>>* read_data(string fn, int V) {
    list<pair<int, int>>* graph = new list<pair<int, int>> [V + 1]();
    fstream filestr;
    string buffer;
    filestr.open(fn.c_str());
    if (filestr.is_open())
        while (getline(filestr, buffer)) {
            string buffer2;
            stringstream ss;
            ss.str(buffer);
            vector<string> tokens;
            while (ss >> buffer2)
                tokens.push_back(buffer2);
            int vertex1 = atoi(tokens[0].c_str());
            for (unsigned int i = 1; i < tokens.size(); i++) {
                int pos = tokens[i].find(",");

                int weight = atoi(tokens[i].substr(0, pos).c_str());
                int vertex2 =
                        atoi(
                                tokens[i].substr(pos + 1,
                                        tokens[i].length() - 1).c_str());
                graph[vertex1].push_back(make_pair(weight, vertex2));
            }
        }
    else {
        cout << "Error opening file: " << fn << endl;
        exit(-1);
    }
    return graph;
}

void compute_shortest_paths_to_all_vertices(list<pair<int, int>>* g, int V,
    int source, int* distance) {
list<int> S;
set<int> V_S;
for (int i = 1; i <= V; i++) {
    if (i == source) {
        S.push_back(i);
        distance[i] = 0;
    } else {
        V_S.insert(i);
        distance[i] = INT_MAX;
    }
}
while (!V_S.empty()) {
    int v1 = S.back();
    for (pair<int, int> w_v : g[v1]) {
        int weight = w_v.first;
        int v2 = w_v.second;
        bool is_in_V_S = V_S.find(v2) != V_S.end();
        if (is_in_V_S)
            if (distance[v1] + weight < distance[v2])
                distance[v2] = distance[v1] + weight;
    }
    int min = INT_MAX;
    int pmin = -1;
    for (int v2 : V_S) {
        if (distance[v2] < min) {
            min = distance[v2];
            pmin = v2;
        }
    }
    // The graph might not be connected
    if (pmin == -1)
        break;
    S.push_back(pmin);
    V_S.erase(pmin);
}

}

int main(int argc, char **argv) {
    int V = 6;
    list<pair<int, int>>* graph = read_data("TOY_GRAPH.txt", V);
int* shortest_path_distances = new int[V + 1];
int v1 = 1;
compute_shortest_paths_to_all_vertices(graph, V, v1,
        shortest_path_distances);
for (int v2 = 1; v2 <= V; v2++)
    printf("vertex:%d to vertex:%d shortest path distance=%d\n", v1, v2,
            shortest_path_distances[v2]);

}

你能借给我一个人吗?

txt文件的结构:

1 2,2 6,3
2 2,1 3,3 1,4
3 6,1 3,2 4,4 3,5
4 1,2 4,3 2,5 10,6
5 3,3 2,4 5,6
6 10,4 5,5

1 个答案:

答案 0 :(得分:0)

如果filestr.open失败,则该文件可能不在程序查找目录中。

对于调试,您可以打印当前目录,以便了解程序在哪里查找文件。

例如在Windows上你可以这样做:

char cd[100];
_getcwd( cd, 100 );
cout << cd << endl;