字符串在find_last_of()和substr()之后变为空?

时间:2012-04-15 02:38:29

标签: c++

自我教导C ++,我知道我错过了一些批判性的东西,但我不能为我的生活弄清楚它是什么。

原谅大量的代码,我很想把它修改为关键元素,但我想如果我把它完好无损,你们可能会对我的编码风格有其他的教育批评......

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

//  main routine
int main(int argc, char *argv[]) {
    // will store filetype here for later
    string filetype = "";
    string filename;

    // if no arguments, die.
    if (argc < 2) {
        cout << "ERROR: Nothing to do." << endl;
        return 1;
    }

    // if more than one argument, die.
    else if (argc > 2) {
        // TODO: support for multiple files being checked would go here.
        cout << "ERROR: Too many arguments." << endl;
        return 1;
    }

    // otherwise, check filetype
    else {
        string filename = argv[1];
        cout << "Filename: " << filename << endl;
        //searching from the end, find the extension of the filename
        int dot = filename.find_last_of('.');
        if (dot == -1){
            // TODO: Add support for filenames with no extension
            cout << "ERROR: Filename with no extension." << endl;
            return 1;
        }
        string extension = filename.substr(dot); 
        if (extension == ".htm" || extension == ".html"){
            filetype = "html";
        }
        else if (extension == ".c"){
            filetype = "c";
        }
        else if (extension == ".c++" || extension == ".cpp") {
            filetype = "cpp";
        }
        else {
            cout << "ERROR: unsupported file extension" << endl;
            // TODO: try to guess filetype from file headers here
        }
    }

    cout << "Determined filetype: " << filetype << endl;
    cout << "Filename: " << filename << endl;

    return 0;
}
                                            // All done :]

我遇到的问题很神秘。我把参数传递给了一个像这样的字符串:

string filename = argv[1];

然后搜索它的扩展名,从最后开始并按照我的方式开始:

int dot = filename.find_last_of('.');
string extension = filename.substr(dot);

这一切都按预期工作,但之后,当我尝试输出文件名时,它是神秘的空?我试着用cout调试。当我在搜索它之前打印出字符串时,它会正确打印。之后,没有打印。像这样:

$ g++ test.cpp -o test.out; ./test.out foo.html
Filename: foo.html
Determined filetype: html
Filename:

我记得过去有关迭代器的事情,并尝试使用filename.begin()重置它,但这没有做任何事情。有人能解释这个令人费解的问题吗?

1 个答案:

答案 0 :(得分:3)

您在else

之后声明了名为filename的第二个变量
string filename = argv[1];

当你到达目的地时,这超出了范围:

 cout << "Filename: " << filename << endl;

您现在正在filename下方打印您声明为main的第一个变量的内容。