我有这个代码从文件中读取它的工作原理。
#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],(或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)
你能否建议我从包含任何类型数据的文件中读取的方式(double,float等)。非常感谢你。
答案 0 :(得分:0)
你能否建议我从包含数据的文件中读取的方式 任何类型(双,浮动等)。
怎么样这样:
ifstream inf;
double d;
int n, m;
inf.open("foo.txt", ios::in);
inf >> d >> n >> m;
inf.close();
答案 1 :(得分:0)
您可以使用以下模板:
#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
)