2013-09-28 126 views
-2

大家好,我正尝试从C++中的文件中读取数据。我是新来的C++,但从文件测试程序实践一个简单的读取。我的程序编译,但是当我从一个文件读取时,它会在屏幕上显示一堆垃圾。以下是我的代码:需要帮助从文件读取。 C++

#include <iostream> 
#include <fstream> 

int main() 
{ 
    ifstream infile; 
    char File[20]; 
    cout<<"Please enter file name: "<<endl; 
    cin>>File; 
    string sym; 
    double o_price, h_price, l_pprice, c_pprice, c_price; 
    int o_shares; 

    infile.open(File); 

    if(!infile.is_open()) 
    { 
     cout<<"The file cannot be open"<<endl; 
    } 

    while(!infile.eof()) 
    { 
     infile>>sym>>o_price>>c_price>>h_price>>l_pprice>>c_pprice>>o_shares; 
     cout<<sym<<o_price<<c_price<<h_price<<l_pprice<<c_pprice<<o_shares; 
    } 
    infile.close(); 
    return 0; 
} 

请我需要帮助,因为我想了解这个概念。 对于缺少的语法感到抱歉。 输入文件包含: ABC 120.09 123.11 134.45 124.34 36.67 10000

下面是在屏幕上显示的输出:! P =环R {[CONTENT_TYPES] .xml000000e?。

+3

你错过了一半的代码,在这里。什么是“sym”,“o_price”等?你也没有显示文件中的内容。 –

+0

此代码不会按给定的方式编译。您需要发布完整且完整的源代码。 –

+0

对不起,我确实声明这些变量只是忘记将它们添加到代码中。但我编译,它仍然在屏幕上显示垃圾。 – Emy

回答

0
#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    ifstream infile; 
    char File[20]; 
    cout<<"Please enter file name: "<<endl; 
    cin>>File; 
    infile.open(File); 

    if(!infile.is_open()) 
    { 
     cout<<"The file cannot be open"<<endl; 
    } 

    string sym; 
    double o_price, h_price, l_pprice, c_pprice; 
    int o_shares; 
    infile>>sym>>o_price>>h_price>>l_pprice>>c_pprice>>o_shares; 
    cout<<sym<<" "<<o_price<<" "<<h_price<<" " 
     <<l_pprice<<" "<< c_pprice<<" "<<o_shares<< endl; 

    infile.close(); 
    return 0; 
} 
+1

这不可能是正确的,OP说代码编译,它不会出现这些错误。发布的代码一定是坏的。 –

+0

它不会编译这些项目丢失。 –

+0

对不起,我已经宣布了你们正在谈论的变数,但忘记写出来。它编译但在屏幕上显示垃圾。 – Emy

1

您需要在使用它之前定义或声明变量。 但是,在您的程序中,sym, o_price, h_price, l_pprice, c_pprice, o_shares未定义或未声明。 Cpp是一种静态语言,您需要遵守规则。

+0

我确定他们只是忘了写出来。抱歉忘记了。 – Emy

0

尝试修改此:

if(!infile.is_open()) 
{ 
    cout<<"The file cannot be open"<<endl; 
} 

这样:

if(!infile.is_open()) 
{ 
    cout<<"The file cannot be open"<<endl; 
    return 0; 
} 

当你拥有了它,现在,你检查文件是否被成功打开,但如果它不是,你只是继续你的程序。如果文件没有正确打开,您不想这样做,因为它会继续读取(不成功)并永久打印垃圾值。

而且,这样的:

while(!infile.eof()) 

是不是要走的事情以正确的方式,因为后你试图读到文件的最后,你只会得到EOF,所以它我会一直尝试阅读(在你的情况下,打印)一次超过你想要的。

+0

我的确如你所说的保罗,但它仍然在屏幕上显示相同的垃圾 – Emy

+0

我没有使用while循环,但仍得到相同的结果。 – Emy