![](/img/trans.png)
[英]error in file handling in c++--no matching function for call to `std::basic_fstream<char, std::char_traits<char> >::open(const char[8], bool)'
[英]C++ error in cygwin; no matching function for call to 'std::basic_fstream…'
我在Windows 10上使用cygwin。當我嘗試運行一個非常簡單的程序時,該程序顯示從文件到命令提示符的行,但出現此錯誤:
$ c++ -c test.cpp
test.cpp: In function ‘int main()’:
test.cpp:9:31: error: no matching function for call to ‘std::basic_fstream<char>::open(std::string&, const openmode&)’
myfile.open(filename, ios::in);
^
In file included from test.cpp:2:0:
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/fstream:1001:7: note: candidate: 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/5.4.0/include/c++/fstream:1001:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
我以為這是本地安裝問題,但是我在第二台計算機上安裝了cygwin,並且發生了同樣的事情。 我很茫然。
邊注; 當我包含ifstream標頭時,錯誤更改為“致命錯誤:ifstream:沒有這樣的文件或目錄。
這是我的代碼:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string filename="names.txt";
fstream myfile;
myfile.open(filename, ios::in);
string firstname, lastname, id;
for (int i = 0; i < 1; ++i)
{
myfile >> firstname >> lastname >> id;
cout << firstname << " " << lastname << id <<endl;
}
return 0;
}
任何幫助將非常感激! 這是我在這里的第一篇文章,因此,如果我有任何虛假行為,請告訴我。
看來您需要#include <string>
:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
...
string
include是由某些編譯器自動添加的,但看來這不是其中之一。
它從編譯器中清楚地表明: no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const char*
'
所以你必須使用c string
而不是std::string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.