我正在尝试使用getline直接从控制台获取用户输入到C ++字符串对象中。但是我没有这样做,因为编译器给了我以下错误。
main.cpp: In function ‘int main(int, char**)’:
main.cpp:52:28: error: no matching function for call to ‘std::basic_ifstream<char>::getline(std::ifstream&, std::string&)’
main.cpp:52:28: note: candidates are:
/usr/include/c++/4.6/istream:599:5: note: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::getline(std::basic_istream<_CharT, _Traits>::char_type*, std::streamsize, std::basic_istream<_CharT, _Traits>::char_type) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::char_type = char, std::streamsize = int]
/usr/include/c++/4.6/istream:599:5: note: candidate expects 3 arguments, 2 provided
/usr/include/c++/4.6/istream:408:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::getline(std::basic_istream<_CharT, _Traits>::char_type*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>, std::basic_istream<_CharT, _Traits>::char_type = char, std::streamsize = int]
/usr/include/c++/4.6/istream:408:7: note: no known conversion for argument 2 from ‘std::string {aka std::basic_string<char>}’ to ‘int’
以下是源代码:
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <cstdio>
#define MAX_LIN 1024
using namespace std;
typedef set<int> si;
int main(int argc, char** argv)
{
string line1;
string line2;
map <string , si > iMap;
if (argc != 3) {
fprintf(stderr,"Usage: a.out <file1> <file2>\n");
}
ifstream f1,f2;
f1.open(argv[1],ifstream::in);
f2.open(argv[2],ifstream::in);
while(!f1.eof()) {
getline(f1,line1);
mParse(line1);
}
while(!f2.eof()) {
f2.getline(f2,line2);
mParse(line2);
}
f1.close();
f2.close();
return 0;
}
答案 0 :(得分:6)
这是原因:
f2.getline(f2,line2);
应该是:
getline(f2,line2);
有一个std::ifstream::getline()
,但它接受不同的论点。
请注意while
循环的结构不正确,因为在读取操作后应立即检查eof()
。编码循环的常用方法是:
while (getline(f2, line2))
{
mParse(line2);
}
答案 1 :(得分:0)
以下是规范方式:
std::ifstream f1(argv[1]);
std::ifstream f2(argv[2]);
for (std::string line; std::getline(f1, line); )
{
mparse(line);
}
for (std::string line; std::getline(f2, line); )
{
mparse(line);
}
请注意我们不写的所有内容,其中每一项都应被视为大写罪:eof
,open
,close
,{{1} },ifstream::in
。