读取除此输入字符串的最后一个字符以外的所有字符?

时间:2013-12-17 04:55:34

标签: c++

不幸的是,这只是在顶点A - F而不是G中读取。基本上在这个循环while(input.find(' ', pos1) != string::npos)中,它比我想要的更早终止一个字符,但我不确定要改变什么。我创建此代码只是为了通过重定向读入输入,并创建一个顶点映射和一个图形的字符向量。它不是很优雅所以如果你想在输入中建议一种更有效的阅读方式那么这也很好。谢谢!

void MSTapp::processFile()
{
int pos1;
int pos2;
map<char, Vertex*> adjacencyList;
vector<char> listOrder;
string input;
bool test = false;
while (getline(cin, input)) {
    pos1 = pos2 = 0;
    if(std::string::npos != input.find_first_of("0123456789"))
    {

        char source = input[0];
        char destination = input[2];
        stringstream ss(input.substr(4));       
        int weight;
        ss >> weight;
        Edge newEdge(destination, weight);
        adjacencyList[source]->addEdge(destination, newEdge);
        Edge roadBack(source, weight);
        adjacencyList[destination]->addEdge(source, roadBack);
    }
    else
    {
        while(input.find(' ', pos1) != string::npos)
        {
            pos2 = input.find(' ', pos1);
            char vertex = input[pos1];
            listOrder.push_back(vertex);
            Vertex* newVertex = new Vertex(vertex);
            adjacencyList.insert(make_pair(vertex, newVertex));
            pos1 = pos2 + 1;
        };
    };
};
Graph graph(listOrder, adjacencyList);
prim(graph, adjacencyList[listOrder[0]]);
}

输入

A B C D E F G
A B 3
A E 4
B C 7 
B E 6
B F 5
C D 9
C F 8
D F 9
D G 4
E F 6
F G 8

1 个答案:

答案 0 :(得分:1)

while(input.find(' ', pos1) != string::npos)无法找到空格字符的迭代中,input[pos1]指向最后一个非空格字符。

那是因为空格在字符之间,而不是在它们之后。这有时被称为&#34; fencepost错误&#34;。它来自一个逻辑难题:&#34;假设你想沿着一条10米的长度放一个围栏,每隔1米有一个围栏。你需要多少个栅栏?&#34; 10似乎是明显的答案,但11是更好的答案,因为10个差距需要11个fenceposts。同样的想法在这里。

编写逻辑的一种更明显的方法是搜索字符,而不是它们之间的空格。例如:

    while( (pos2 = input.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ", pos1)) != string::npos)
    {
        char vertex = input[pos2];
        listOrder.push_back(vertex);
        Vertex* newVertex = new Vertex(vertex);
        adjacencyList.insert(make_pair(vertex, newVertex));
        pos1 = pos2 + 1;
    }

请注意,您必须将pos1pos2的声明更改为std::string::size_type pos1, pos2;。实际上,您不需要两个单独的pos变量:

    std::string::size_type pos = 0;

    while( (pos = input.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ", pos)) != string::npos)
    {
        char vertex = input[pos];
        listOrder.push_back(vertex);
        Vertex* newVertex = new Vertex(vertex);
        adjacencyList.insert(make_pair(vertex, newVertex));
        ++pos;
    }