【发布时间】:2014-03-06 12:37:52
【问题描述】:
我想知道如何使用流读取文件以及在函数中使用它们。 到目前为止,我的代码是;:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
void burbuja(int[]);
void imprimeArreglo (int[],int);
void leeArchivo(string&);
int arreglo[10];
int i;
void burbuja (int a[])
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<i;j++)
{
if(a[i]>a[j])
{
int temp=a[i]; //swap
a[i]=a[j];
a[j]=temp;
}
}
}
}
void imprimeArreglo(int a[],int tam)
{
for(int i=0;i<tam;i++)
cout << a[i] << " ";
}
void leeArchivo(string& nombre)
{
string filename = nombre;
ifstream myfile(filename);
string line;
if (myfile.is_open()) {
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
}
int main()
{
string nombre = "arr.txt";
leeArchivo(nombre);
cin >> i ;
return 0;
}
我希望能够从 main 方法调用 leeArchivo("arr.txt")。 有了这个我得到了错误:
Error: bubble.cpp(37,14):'ifstream' is not a member of 'std'
Error: bubble.cpp(37,19):Statement missing ;
Error: bubble.cpp(39,20):Undefined symbol 'file'
Error: bubble.cpp(39,25):Could not find a match for 'std::getline(undefined,std::basic_string<char,std::string_char_traits<char>,std::allocator<char>>)'
我在这里缺少什么? (我是 C++ 新手)
我要读取的文件具有以下结构:
<number>
<number> <number> <number> ...
例如:
5
19 28 33 0 1
===========================================
编辑: 我使用的是 Borland C++ 5.02
编辑 2:
更新代码,使用 Geany 现在错误是:BUBBLE.cpp:38:25: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'
【问题讨论】:
-
1) 你的 main 函数没有返回类型,2) 你
using namespace std;但在某些地方仍然放了std::。只需删除 using 指令并指定std::, 3) @987654321 @绝对是命名空间std::的成员 -
也就是说,您使用的是什么编译器? (我很惊讶它没有提到 main 没有返回类型)
-
在
main()、this should compile correctly的非标准声明之外。无论您在发布时从代码中剥离了什么,都将其放回并更新帖子。这样做时,还要添加您正在构建的编译器和平台。 (我会使用cstdlib,但这不应该导致您遇到的问题;您不显示的代码对此负责)。报告的错误声称它们位于第 37 和 39 行。显然缺少某些内容。 -
刚刚添加了整个代码。