2013-12-17 68 views
0

我在尝试读取外部文本文件时遇到问题。 显示的文本是正确的,但是当涉及到将数据保存到数组中时,它似乎是错误的。ifstream尝试将数据保存到数组时遇到错误

我的输入数字是4 2 8 0 2 3 0 4 0 5,但是在遍历数组后,a [i]只出现'48'。

#include <iostream> 
#include <windows.h> 
#include <fstream> 
#include <string> 

void begin(); 
void Process (string); 

using namespace std; 

int main() 
{ 

     begin(); 

     system("pause"); 
     return 0; 
} 

void begin (void){ 

string file = "data.txt"; 
Process(file);  
} 

void Process (string file) 
{ 

     int i=0,ch, n = 0, temp, a[50]; 


     ifstream infile; 
     infile.open(file.c_str()); 

该错误似乎是由此引起的。

 if(infile.is_open()) 
     { 

      cout << "File to be read: " << file << endl; 
      cout << "\n\n"; 
      infile >> temp; 
      while(!infile.fail()) 
      { 
       cout << temp << " "; 
       infile >> temp; 
       a[i] = temp; 
       i++; 
       n++; 
      } 

     cout << "\n\n"; 
     cout << "This file has " << n << " numbers. \n\n"; 

     } 

     else 
      cout << "The file isn't available! \n\n"; 

     infile.close(); 

当我尝试输出结果时,只出现了48。

 for (int z = 0; z < i; z++) 
     { 
      cout << a[i] << endl; 

     } 
} 

我是新来的。请帮忙。提前致谢。

回答

1

您的显示回路使用i代替z索引到a(这应该是为什么变量命名是很重要的一个很好的教训!)你的显示器循环改成这样:

for (int z = 0; z < i; z++) 
    { 
     cout << a[z] << endl; 
    } 

有可能更问题与您的代码,但这似乎是什么阻止你。考虑将ia重命名为更有意义的事情。花费在打字上的时间总是会让你花费时间去理解你的意思。

0

考虑这个循环

for (int z = 0; z < i; z++) 
    { 
     cout << a[i] << endl; 

    } 

你总是输出一个元素的[I]而不是[Z]。此外,索引为i的元素未分配。最后指定的元素是[i-1]。

除此之外,您不会将第一个输入的数字保存在数组中。您开始保存来自第二个号码的输入数据。

 infile >> temp; // <== this value was not assigned to an element of the array 
     while(!infile.fail()) 
     { 
      cout << temp << " "; 
      infile >> temp; 
      a[i] = temp; 

而且循环

  infile >> temp; 

这里面的语句可能会导致错误。所以之后没有意义写

  a[i] = temp; 

因为没有输入任何内容,事实上你会将前一个数字存储在下一个元素中。

相关问题