2012-04-15 23 views
0

自學自我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()重置它試圖,但這也沒做。有人可以解釋這個令人困惑的問題嗎?

+1

我們實際上只喜歡關鍵元素。 http://sscce.org/ – chris 2012-04-15 02:41:48

+0

然後跳過代碼,只讀底部:] – 2012-04-15 02:42:23

回答

3

您聲明名爲filename這裏第二個變量中,else後:

string filename = argv[1]; 

這由時間超出範圍,你在這裏:

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

您正在打印的內容你聲明的第一個變量叫做filename,正好在main之下。

+0

啊,哇。這是非常簡單的,不能相信這是我錯過了。謝謝! – 2012-04-15 02:51:44

+1

@betaRepeating通常編譯器對此有警告。始終確保您的程序沒有警告,並儘可能多地啓用警告。例如,鏗鏘和我假設gcc會直接指向這個變量,並說,如'警告:聲明陰影局部變量'如果你打開-Wshadow或 - 一切 – bames53 2012-04-15 03:31:48

相關問題