自学 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()
它来重置它,但这没有任何作用。有人可以阐明这个令人费解的问题吗?