【问题标题】:Does getline in C++ just take string type?C++ 中的 getline 是否只采用字符串类型?
【发布时间】:2013-11-19 19:11:34
【问题描述】:

我有这个代码可以从文件中读取,它可以工作。

#include "cppstd.hh"
#include <string>

int main(){
  string line;
  string *vdata= new string[10];
  ifstream fvecin ("vector.txt");
  if (fvecin.is_open()){
    for (int i=0;i<10;i++){
      getline(fvecin,line);
      vdata[i]=line;
      cout << "vdata["<<i<<"]="<< line << endl;
      }
    }
  else{
    cout << "ERROR: Cannot open the file!" << endl;
  }

  return 0;
}

但是,当我更改为 int 行时, int *vdata = new int[10],(or double) 它不起作用并出现此错误:

ifstream_test.cc: In function ‘int main()’:
ifstream_test.cc:10:26: error: no matching function for call to ‘getline(std::ifstream&, int&)’
ifstream_test.cc:10:26: note: candidates are:
/usr/include/stdio.h:675:20: note: __ssize_t getline(char**, size_t*, FILE*)
/usr/include/stdio.h:675:20: note:   candidate expects 3 arguments, 2 provided
/usr/include/c++/4.6/bits/basic_string.h:2734:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_istream<_CharT, _Traits>& std::getline(std::basic_istream<_CharT, _Traits>&, std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/include/c++/4.6/bits/basic_string.tcc:1070:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_istream<_CharT, _Traits>& std::getline(std::basic_istream<_CharT, _Traits>&, std::basic_string<_CharT, _Traits, _Alloc>&, _CharT)

您能否建议我从包含任何类型(双精度、浮点等)数据的文件中读取的方式。非常感谢。

【问题讨论】:

  • 文件是以二进制格式还是文本格式存储这些值?

标签: c++ ifstream getline


【解决方案1】:

您能否建议我从包含数据的文件中读取的方式 任何类型(double、float 等)。

这样试试怎么样:

ifstream inf;
double d;
int n, m;

inf.open("foo.txt", ios::in);

inf >> d >> n >> m;

inf.close();

同时检查Input/Output with files

【讨论】:

  • 成功了。非常感谢!!
  • @user2969181:- 如果这对你有用,你可以接受这个作为答案:)
  • 我认为使用 inf >> 的建议很有帮助。其实我之前就知道了。
【解决方案2】:

您可以使用这样的模板:

#include <iostream>
#include <string>
#include<fstream>
#include<vector>
#include<algorithm>
#include<iterator>

template <typename T>
std::vector<T> ReadFile( std::string fname)
{

  std::vector<T> vec;
  std::ifstream fvecin (fname.c_str());
  if (fvecin.is_open()){
   std::copy(std::istream_iterator<T>(fvecin),
             std::istream_iterator<T>(), std::back_inserter(vec) );
    }
  else{
    std::cout << "ERROR: Cannot open the file!" << std::endl;
  }
return vec;
}

然后,

#define READ_TYPE float //change type here
int main(){

std::vector<READ_TYPE> v;
  v=ReadFile<READ_TYPE>(std::string("input.txt"));

for(auto i:v)
std::cout<<i<<" "<<std::endl;

  return 0;
}

'here'(用std::cin代替std::ifstream

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多