有時候我在代碼中發現了令人難以置信的長錯誤,我不明白,所以我只是重寫我的代碼以避免造成錯誤。今天我有另外一個,我根本無法避免。很長,幾乎不相關的錯誤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++中常見的錯誤?謝謝。
在發佈之前,您是否打擾閱讀您的代碼?你的第一個錯誤只是一個錯字... –
看着你的問題歷史,看來,這個軟件開發不適合你。聽起來很刺耳,你會在其他地方過上更幸福的生活。 – IInspectable
@IIpectable絕對苛刻。可能會更好地推薦一本好的C++書... –