我使用Visual Studio 2012和C ++编写了一个C ++杂货库存程序 一切顺利,如预期的那样。文件作为命令行参数读入,用于填充带有Grocery对象的双端队列。我用来检查Grocery对象是否即将到期的函数很快就使用了time_t和struct tm。当我尝试在Unix上运行我的程序时,我得到一个涉及fstream的错误
以下是我收到错误的代码行:
int main (int argc, char** argv) {
deque<Grocery> groceries;
deque<Grocery>::iterator iter;
string filename = "";
if (argc > 1) {
filename = argv[1];
fstream fileData;
fileData.open(filename, ios::in | ios::out); //**error**
//error check
if (!fileData) {
cout << "Error openeing file. Program aborting.\n";
return 1;
}
string name;
string expDate;
string type;
string quantity;
while (!fileData.eof()) {
Grocery temp;
getline (fileData,name,'\t');
temp.setName(name);
getline (fileData,expDate,'\t');
temp.setExpDate(expDate);
getline (fileData,type,'\t');
temp.setType(type);
getline (fileData, quantity,'\n');
temp.setQuantity(atoi (quantity.c_str()));
groceries.push_back(temp);
}
fileData.close();
}
return 0;
}
尝试在Unix中运行程序时出现错误
$ make all
g++ -c Grocery.cpp
g++ -c Inventory.cpp
Inventory.cpp: In function âint main(int, char**)â:
Inventory.cpp:24:45: error: no matching function for call to âstd::basic_fstream<char>::open(std::string&, std::_Ios_Openmode)â
fileData.open(filename, ios::in | ios::out);
^
Inventory.cpp:24:45: note: candidate is:
In file included from Inventory.cpp:3:0:
/opt/rh/devtoolset-2/root/usr/include/c++/4.8.1/fstream:886: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,
^
/opt/rh/devtoolset-2/root/usr/include/c++/4.8.1/fstream:886:7: note: no known conversion for argument 1 from âstd::string {aka std::basic_string<char>}â to âconst char*â
make: *** [Inventory.o] Error 1
生成文件
MKFILE = Makefile
#
# Definitions of list of files:
#
HSOURCES = Grocery.h
CSOURCES = Grocery.cpp Inventory.cpp
ETCSRC = README ${MKFILE}
EXECBIN = main
ALLCSRC = ${CSOURCES}
OBJECTS = ${ALLCSRC:.cpp=.o}
ALLSRC = ${ETCSRC} ${HSOURCES} ${CSOURCES}
LISTSRC = ${ALLSRC}
#
# Definitions of the compiler and compilation options:
#
GCC = g++
#
# The first target is always ``all'', and hence the default,
# and builds the executable images
#
all : ${EXECBIN}
#
# Build the executable image from the object files.
#
${EXECBIN} : ${OBJECTS}
${GCC} -o ${EXECBIN} ${OBJECTS}
#
# Build an object file form a C source file.
#
%.o : %.cpp
${GCC} -c $<
#
# Clean and spotless remove generated files.
#
clean :
- rm -rf ${EXECBIN} ${OBJECTS}
固定 答案如下所列
答案 0 :(得分:2)
Inventory.cpp:24:45: error: no matching function for call to âstd::basic_fstream<char>::open(std::string&, std::_Ios_Openmode)â
fileData.open(filename, ios::in | ios::out);
basic_fstream(const string&, ios_base::openmode)
构造函数仅在C ++ 11模式下可用。
您正在以C ++ 98模式编译代码。编译时将-std=gnu++11
传递给g++
。
答案 1 :(得分:1)
我认为你需要一个干净的构建。 由于您在头文件中有声明,并且您可能已将expDate从类型tm更改为tm *。