2016-02-14 31 views
-10

有時候我在代碼中發現了令人難以置信的長錯誤,我不明白,所以我只是重寫我的代碼以避免造成錯誤。今天我有另外一個,我根本無法避免。很長,幾乎不相關的錯誤C++

我的代碼:

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cctype> 
#include <vector> 

using namespace std; 

void readFile(string); 

class info { 
    public: 

    int rows; 
    int cols; 
    vector <string> data; 
}; 

int main(int argc, char **argv){ 

    string filename1; 
    filename = argv[1]; 
    readFile(filename); 

    return 0; 
} 

//should read onle line at a time from a file and print it 
void readFile(string filename1){ 
    fstream datafile; 
    datafile.open(filename1); 

    while (!datafile.eof()){ 
      string line; 
      getline(datafile,line); 
      cout<<line<<endl; 
    } 

    datafile.close(); 
} 

錯誤從試圖獲得該文件的argv的,從名字源於[1]。當我給它的文件名時它工作正常。

錯誤:

project2.cpp: In function ‘int main(int, char**)’: 
project2.cpp:22:2: error: ‘filename’ was not declared in this scope 
    filename = argv[1]; 
^
project2.cpp: In function ‘void readFile(std::string)’: 
project2.cpp:32:25: error: no matching function for call to  ‘std::basic_fstream<char>::open(std::string&)’ 
    datafile.open(filename1); 
        ^
project2.cpp:32:25: note: candidate is: 
In file included from project2.cpp:2:0: 
/usr/lib/gcc/x86_64-pc-cygwin/4.9.3/include/c++/fstream:889:7: note: void  std::basic_fstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode)  [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode =  std::_Ios_Openmode] 
     open(const char* __s, 
    ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.3/include/c++/fstream:889:7: note: no  known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’  to ‘const char*’ 

我使用Cygwin的。我在上個學期使用它,當時我正在用C編寫代碼,而且我的教授讓我們在當時檢查某些安裝選項。這些安裝選項可能是問題的根源嗎?還是像C++中常見的錯誤?謝謝。

+4

在發佈之前,您是否打擾閱讀您的代碼?你的第一個錯誤只是一個錯字... –

+0

看着你的問題歷史,看來,這個軟件開發不適合你。聽起來很刺耳,你會在其他地方過上更幸福的生活。 – IInspectable

+2

@IIpectable絕對苛刻。可能會更好地推薦一本好的C++書... –

回答

1

只需讀取錯誤:

project2.cpp: In function ‘int main(int, char**)’: project2.cpp:22:2: error: ‘filename’ was not declared in this scope filename = argv[1]; ^

這說filename沒有聲明。即你必須聲明它還是有點問題的聲明

看代碼,你有

string filename1; 

我們假設你的意思是

string filename; 

修復這個錯誤 - 然後再次嘗試

+0

感謝您至少回答我的部分問題。 – SchmitsNGiggles

+0

我發現我的問題的根源在於我必須在打開的函數中將「.c_str()」放在「filename1」之後,這發生的原因很簡單,因爲我從來沒有在C++中使用此方法打開文件。 – SchmitsNGiggles

+1

請在將來閱讀錯誤消息「不匹配調用...的函數」,然後閱讀您要調用的方法的手冊頁 –

0

第一個錯誤:將filename1更改爲filename 第二個錯誤:您應該在類info.then中設置一個open()函數,然後您可以使用它