我有一个名为file.dat的文件,其中包含三列和数字。文件内容如下
2.30276e-07 1.73472e-18 -2.31198e-07
6.94031e-07 1.99493e-17 -2.30956e-07
1.15043e-06 -6.93889e-18 -2.25137e-07
1.58577e-06 -8.67362e-19 -2.12817e-07
1.99688e-06 1.64799e-17 -1.94697e-07
2.39116e-06 -5.20417e-18 -1.98568e-07
2.76304e-06 3.46945e-18 -1.7162e-07
3.06033e-06 -2.60209e-17 -1.24218e-07
3.25685e-06 -1.47451e-17 -7.85356e-08
我需要读取文件并将列号存储在其中。
std::string s;
std::ifstream in("file.dat");
double a[10], b[10],c[10] ;
for(int i=0;i<10;i++)
{
std::getline(in, s);
s >>a[i] >>b[i] >>c[i] ;
}
但有了这个,我得到错误
flux.cpp:117:7: error: no match for ‘operator>>’ in ‘s >> aa’
flux.cpp:117:7: note: candidates are:
/usr/include/c++/4.6/bits/basic_string.tcc:998:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/include/c++/4.6/bits/istream.tcc:957:5: note: template<class _CharT2, class _Traits2> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, _CharT2*)
/usr/include/c++/4.6/bits/istream.tcc:925:5: note: template<class _CharT, class _Traits> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, _CharT&)
/usr/include/c++/4.6/istream:709:5: note: template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, unsigned char&)
/usr/include/c++/4.6/istream:714:5: note: template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, signed char&)
/usr/include/c++/4.6/istream:756:5: note: template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, unsigned char*)
/usr/include/c++/4.6/istream:761:5: note: template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, signed char*)
如何正确读取文件中的数字?
答案 0 :(得分:1)
&#34;我如何才能正确读取文件中的数字?&#34;
std::string
并未提供operator>>
,因为您正在尝试使用它。请改用std::istringstream
std::getline(in, s);
istringstream iss(s);
iss >>a[i] >>b[i] >>c[i] ;
也不要忘记正确的#include
陈述。
由于您的文件只包含double
个值,您还可以考虑完全省略getline()
。您可以按如下方式编写循环
for(int = 0; i < 10 && in >>a[i] >>b[i] >>c[i]; ++i);
答案 1 :(得分:1)
你可以简单地做
std::ifstream in("file.dat");
double a[10], b[10],c[10] ;
for(int i=0;i<10;i++)
{
in >>a[i] >>b[i] >>c[i] ;
}
,因为istream
&#39; s operator>>
跳过换行符,就像默认情况下跳过空格一样。