2014-11-23 104 views
0

我一直在玩这个,但我没有得到任何帮助。我正在尝试从txt文件读取整数列表到一个数组(1,2,3,...)。我知道将被读取的整数的数量是100,但我似乎无法填充数组。每次我运行代码本身时,它仅为所有100个整数存储值0。有什么想法吗?从文本文件读入数组

//Reads the data from the text file 
void readData(){ 
ifstream inputFile; 
inputFile.open("data.txt"); 

if (!inputFile){ 
    //error handling 
    cout << "File can't be read!"; 
} 
else{ 
    int a; 
    while (inputFile >> a){ 
     int numbers; 
     //Should loop through entire file, adding the index to the array 
     for(int i=0; i<numbers; i++){ 
      DataFromFile [i] = {numbers}; 
     } 
    } 
} 

}

回答

0

要阅读从istream的一个整数,你可以做

int a; 
inputFile >> a; 

这是你在你的while循环做什么。 虽然对于流中每个整数(在文件中)您都将执行遗嘱块,但这是好事

这个inputFile >> a一次读取一个整数。如果放入测试(如果/当),真值将回答“问题是否已读取?”这个问题。

我没有得到你想要和你做什么number变量。正如不是由你初始化它lloks喜欢它的价值0这最终使得福尔循环无法运行

如果你想读的正是100整数,你可以做

int *array = new int[100]; 
for (int i=0; i<100; ++i) 
    inputFile >> array[i]; 

否则你能保持一个计数器

int value; 
int counter = 0; 
while(inputFile >> value && checksanity(counter)) 
{ 
    array[counter++] = value; 
} 
+0

谢谢您的回答。第一种方法工作,现在我的程序已经启动并运行:) – user3061066 2014-11-24 00:54:10

0

你是不是读a到您numbers,更改代码这样:

if (!inputFile){ 
    //error handling 
    cout << "File can't be read!"; 
} 
else{ 
    int a; 
    while (inputFile >> a){ 
     //Should loop through entire file, adding the index to the array 
     for(int i=0; i<a; i++){ 
      DataFromFile [i] = a; // fill array 
     } 
    } 
} 

如果您是通过文件循环,阵列将使用新的覆盖号码每次。这可能不是你想要做的。你可能想用100个不同的号码填写100个地点?在这种情况下,使用下面的代码:

if (!inputFile){ 
    //error handling 
    cout << "File can't be read!"; 
} 
else{ 
    int i = 0; 
    while (inputFile >> a){ // Whilst an integer is available to read 
     DataFile[i] = a; // Fill a location with it. 
     i++;    // increment index pointer 
    } 
}