2016-02-14 30 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()函数,然后您可以使用它