1

我正在尝试使用 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;
 }   
4

2 回答 2

6

这是原因:

f2.getline(f2,line2);

应该:

getline(f2,line2);

有一个std::ifstream::getline()但它接受不同的论点。

请注意,while循环的结构不正确,eof()应在读取操作后立即检查。编码循环的常用方法是:

while (getline(f2, line2))
{
    mParse(line2);
}
于 2012-10-06T13:01:06.393 回答
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, ifstream::in, return 0.

于 2012-10-06T13:01:20.837 回答