自學自我C++,我知道我錯過了一些關鍵的東西,但我不能爲了我的生活找出它是什麼。find_last_of()和substr()後字符串變空了嗎?
原諒的代碼塊巨大,我很想修剪下來的關鍵要素,但我想如果我離開它的完整,你人可能對我的編碼風格等教育批評......
#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()
重置它試圖,但這也沒做。有人可以解釋這個令人困惑的問題嗎?
我們實際上只喜歡關鍵元素。 http://sscce.org/ – chris 2012-04-15 02:41:48
然後跳過代碼,只讀底部:] – 2012-04-15 02:42:23