【发布时间】:2021-04-17 00:12:35
【问题描述】:
我现在正在编写一个程序,我目前正在尝试从文件中读取输入并将成员放入变量中。当我尝试使用 getline 时,它给了我一个错误。这是我试图从中读取的文本文件中的行。
pontoon,Crest,Carribean RS 230 SLC,1,Suzuki,115,Blue,26,134595.00,135945.00
这是我的构造函数代码:
watercraft::watercraft(ifstream &inFile){
//use getline
//stoi to convert string to int
char tempType[15];
char tempMake[20];
char tempModel[30];
char tempPropulsion[15]; //int
char tempEngine[15];
char tempHp[15]; //int
char tempColor[25];
char tempLength[15]; //int
char tempBase_price[15]; //double
char tempTotal_price[15]; //double
getline(inFile, tempType, ',');
getline(inFile, tempMake, ',');
getline(inFile, tempModel, ',');
getline(inFile, tempPropulsion, ',');
getline(inFile, tempEngine, ',');
getline(inFile, tempHp, ',');
getline(inFile, tempColor, ',');
getline(inFile, tempLength, ',');
getline(inFile, tempBase_price, ',');
getline(inFile, tempTotal_price, ',');
cout << tempType << endl;
}
这是我的mainDriver 代码:
int main(int argc, const char * argv[]){
int choice;
int numFor1 = 0;
ifstream inFile("watercraft.txt");
if(!inFile){
cout << "Something wrong with input file" << endl;
exit(0);
}
do{
choice = printMenu(); //call print menu and assign user input to choice
switch(choice){ //switch statement to do as the user pleases
case 1:
if(numFor1 == 0){ //if file hasnt been initialized
watercraft test(inFile);
numFor1++;
}else{
printf("You have already Initialized list\n"); //if file has been initialized
}
break;
}
}while(choice != 12); //do while user does not want to exit the program
return 0;
}
我遇到了很多错误。这只是一个似乎在getline 的每次迭代中重复出现的错误消息块。
watercraft.cpp:32:5: error: no matching function for call to 'getline'
getline(inFile, tempType, ',');
^~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/stdio.h:355:9: note:
candidate function not viable: no known conversion from
'std::__1::ifstream' (aka 'basic_ifstream<char>') to 'char **' for 1st
argument
ssize_t getline(char ** __restrict __linep, size_t * __restrict __lineca...
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/istream:1507:1: note:
candidate template ignored: could not match
'basic_string<type-parameter-0-0, type-parameter-0-1, type-parameter-0-2>'
against 'char [15]'
getline(basic_istream<_CharT, _Traits>& __is,
【问题讨论】:
-
您使用了错误的
getline。std::getline仅接受std::string。std::istream::getline接受char数组。不过更喜欢std::getline和std::strings。远不那么混乱。 -
旁注:
char tempType[15];定义了构造函数本地的自动变量。一旦构造函数退出,它就会消失,将读入的内容带入其中。如果您只是要将令牌转换为数字或基于它执行计算,那很酷,但很多时候您想直接读取成员变量以在构造函数完成后保留您读取的内容。 -
我建议将错误消息的完整文本添加到问题中。据我所知,我的一位 cmets 已经回答了你的问题,我无法知道。
-
我使用了您的 istream::getline 实现,现在我遇到了一个错误。它说“错误:调用没有对象参数的非静态成员函数”。
-
@Ethan-Eill 我们需要查看该代码并完成错误消息。但很明显,你实际上是在做错误所说的事情 - 尝试调用非静态类方法而不指定要调用该方法的对象。
标签: c++ constructor getline