I am stuck here having trouble figuring out as to why this loop is not inserting the integers from a text file into an array.
I have a textfile that contains 100 integers, all separated by spaces. I am trying to insert these integers into an array. However when I output, for example a[2], it outputs 0, leading me to believe that the numbers are not being inserted into the array.
listFile.open("unsortedlist.txt");
cout << endl << "Unsorted list = ";
for (int i = 0; i < 100; i++)
{
while (listFile >> individualNum )
{
a[i] = individualNum;
cout << individualNum << ", ";
}
}
cout << "\n" << a[1] << "\n";
Because of the while statement, all the numbers that are successfully read are assigned to a[0] only. As a consequence, the final value of a[0] is the last valid input while nothing is assigned to any of the other elements of a.
You can use something like:
for (int i = 0; i < 100 && listFile >> individualNum; i++)
{
a[i] = individualNum;
cout << individualNum << ", ";
}
The inner loop will diligently read every number from the file.
And assign every number to a[i]. The same array element, each and every time.
On the first iteration of the outer loop, i is 0, so the code will read every number from the file, assigning each number to a[0].
When the inner loop reaches the end of the file, it will terminate. Then, the outer for loop will increment i to 1, iterate again, and run the inner loop. Since the entire file has been read, the inner loop will not do anything. Neither it will do anything more, for the remaining 98 elements of the array.
The loop should probably be, simply:
for (int i = 0; i < 100; i++)
listFile >> a[i];
Keep in mind that this will work correctly, of course, only when there are exactly 100 integers in the file.
Related
So I've written this code and it works until I try implemented a part of my second for loop where I try to print a new line. It is suppose to print a new line after the 8th element being printed. Any help appreciated.
// Construct a for loop that runs backwards through the array,
// starting at the last element and ending at the first.
for (int i = arraySize; i > 0; i--) {
// Inside this for loop, print the ith element of the array
// and a tab, with NO newline characters.
cout << newArray[i-1] << " ";
// If this element is the 8th one on its line, print a
// newline character to advance to the next line.
// Also inside this for loop, add the value of the ith
// element to the current value of the double for the sum
// of elements.
//ISSUE IS HERE
if (newArray[i-8] = newArray[7]) {
cout << "\n";
}
sumOfElements += newArray[i-1];
}
I've only pasted the for loop that has the issue, I don't believe any other information is necessary as I know it works up until this point.
You want comparison (==) not assignment (=). But in any case this
if (newArray[i-8] = newArray[7]) {
cout << "\n";
}
is wrong. For i < 8 you will access negative indices, which is out-of-bounds. To check if you are printing the 8th element from the array you only need to look at the index:
if (i == 7) {
cout << "\n";
}
It you rather want to put a new line after 8 elements have been printed then it is
if (i == arraySize-7) {
cout << "\n";
}
If instead you want to put a new line after each 8 elements that have been printed then it is
if ( (i - arraySize - 1)%8 == 0) {
std::cout << "\n";
}
Up until now I've been studying C, and now i wanted to try C++. Started out with some easy tasks. But I can't seem to find the answer, why is there a number either 0 or 488834... printed out.
I've tried re-declaring variables, using
for(n-1; n>=0; n--){
cout << a[n] << endl;
}
int main(){
int var = 0;
int a[100],n;
cin >> n;
for(int i=0; i<n; i++){
cin >> a[i];
var++;
}
for(var-1; var>=0; var--){
cout << a[var] << endl;
}
Everything works, except that 0/some number in the middle of the output
Result
In the following line:
for(var-1; var>=0; var--){
var-1 doesn't actually modify the value of var. So var gets to keep its original value, which means the first value you end up printing is what is after the end of the original sequence.
Use var = var - 1 instead.
In your second for loop you don't have an assignment, just a statement. You start printing from a location of the array that contains an invalid number due to this, you may want too have your second loop read
for(var = var-1; var>=0; var--){
cout << a[var] << endl;
}
Now, there are more element ways to write this, but this is a fix that is needed in your code.
for some reason the first number to print out doesn't abide by the for loop in the main function, telling it to range from 0-10; but when
void printArray(int augArray[5])
{
cout << *augArray; //this line is taken out, the for loop proceeds with normal
for (int i = 0; i < 5;) //outputs, when the first line is kept also the for loop only
{ //produces 4 other numbers, just curious to why this is
cout << augArray[i] << endl; //happening, thanks.
i++;
}
}
int main()
{
srand(time(0));
int anArray[5];
for(int j = 0; j < 5;)
{
anArray[j] = rand() % 11;
j++;
}
printArray(anArray);
cout << anArray;
}
When an array name is used in an expression without square brackets following it, its value is equal to the pointer to the initial element of the array, i.e. augArray in an expression is the same as &augArray[0]. Therefore, *augArray is the same as *(&augArray[0]), which is simply augArray[0] (the asterisk and the ampersand cancel each other).
The reason the output looks strange is that you did not put an end-of-line character after you printed *augArray. The "weird number" that you see in the output is actually the initial element of the array repeated twice.
It should works just fine except the first output is mixed with the following outputs. To see it more clearly, you should put a newline after you print out the first element:
Change
cout << *augArray; // print the first element
to
cout << *augArray << endl; // print the first element and go to a new-line
See it live: http://ideone.com/y16NeP.
Sidenote: you can simply put i++/j++ to the for-line, like for (int i = 0; i < 5; i++).
I am newbie to programming and I am trying to pass an array into a function and add all the elements together and return the sum. The problem is that I am getting a garbage value for the sum. I have researched on how to pass arrays to functions and I do not know if I'm supposed to use a pointer to pass arrays. I am not good with pointers anyways.
Here is my code
#include <cmath>
#include <cstdlib>
using namespace std;
float mean(int);
int sum(int ARRZO[5]);
int total;
int main()
{
int ARRZ[5];
char *inname = "example.txt";
ifstream infile(inname);
if (!infile) {
cout << "There was a problem opening file " << inname << " for reading." << endl;
return 0;
}
cout << "Opened " << inname << " for reading." << endl;
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
total=sum(ARRZ);
cout<<"the sum of the elements in the array is"<<total<<endl;
system("PAUSE");
return 0;
}
int sum(int ARRZO[])
{
int sumz=0;
for (int i=0; i<5; i++)
{
sumz+=ARRZO[i];
cout<<ARRZO[i];
}
cout<<sumz<<endl;
return sumz;
}
You are actually reading all the values from the file in ARRZ[0] because of the inner loop. By the time you get to i=1, you are at the end of the file, and not reading anything.
Remove one loop, and increment i when you have read successfully a value.
I'm not sure what you think this pair of nested loops is supposed to do:
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
But (as #aliexisdm pointed out) the inner loop reads the entire content of the file. What he didn't (at least directly) point out is that you're reading every one of those values into the first element of your array. Then you're getting back to the outer loop, incrementing i, and trying to read the file again -- but since the stream's failbit has been set, all your subsequent attempts at reading are guaranteed to fail.
After that, you add up the 5 items in the array, but since you haven't read anything into 4 of them (and never initialized its contents) you end up with the last item you read from the file + 4 garbage values, giving still further garbage as the result (well, usually anyway -- you really have undefined behavior, so the program could crash and burn instead, but with most current computers, you'll just get some meaningless number).
I, however, would advise changing the program a bit more than just removing one loop and incrementing in the loop that's left. Instead, I'd remove all the (explicit) loops, and make some attempt at making real use of what the standard library provides.
You can read the numbers from the file in one fell swoop:
std::ifstream infile(inname);
std::vector<int> ARRZ ((std::istream_iterator<int>(infile)),
std::istream_iterator<int>());
Then you can sum them all with std::accumulate:
int sum = std::accumulate(ARRZ.begin(), ARRZ.end(), 0);
Finally, you can print out the result:
cout << "The sum of the elements in the array is: " << sum << "\n";
Since, however, you only read the values from the file to add them together, you don't really need to store them at all. You could just add them together and print out the result:
cout << "The sum of the elements in the file is: "
<< std::accumulate(std::istream_iterator<int>(infile),
std::istream_iterator<int>(), 0);
The whole job reduced to one step...
So I create and initialize a vector (of size nmask+3) to 0, and I assign an initial value to one of the elements. I then make a for loop that goes through the first nmask elements of the vector and assigns to each element an average of 26 other elements in the vector (defined by the 4D int array voxt, which contains vector addresses).
My problem is that when I check the values of nonzero elements in my vector (phi) within the nested loop (the first cout), the values are fine and what I expect. However, when the loop finishes going through all nmask elements (for (int i= 0; i<nmask; i++) exits), I check the nonzero elements of phi again, and they are all lost (reset to 0) except for the last non-zero element (and element tvox which is manually set to 1).
I feel that since phi is initialized outside of all the loops, there should be no resetting of values going on, and that any updated elements within the nested loop should remain updated upon exit of the loop. Any ideas as to what is going on / how to fix this? Code is below; I tried to comment in a sense of the outputs I'm getting. Thanks in advance.
vector<double> phi(nmask+3, 0); //vector with nmask+3 elements all set to 0 (nmask = 13622)
phi[tvox]= 1; //tvox is predefined address (7666)
for (int n= 0; n<1; n++)
{
vector<double> tempPhi(phi); //copy phi to tempPhi
for (int i= 0; i<nmask; i++)
{
for (int a= -1; a<=1; a++)
{
for (int b= -1; b<=1; b++)
{
for (int c= -1; c<=1; c++)
{
if (!(a==0 && b==0 && c==0))
{
//oneD26 is just (double) 1/26
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
if (phi[i]!=0)
{
//this gives expected results: 27 nonzero elements (including tvox)
cout << n << " " << i << " " << a << b << c << " " << phi[i] << endl;
}
}
}
}
}
}
phi[svox]= 0; //svox = 7681
phi[tvox]= 1;
for (int q= 0; q<nmask; q++)
{
//this gives only 2 nonzero values: phi[tvox] and phi[9642], which was the last nonzero value from 1st cout
if (phi[q]!=0)
cout << q << " " << phi[q] << endl;
}
}
Difficult to tell just what is going on, but the easiest explanation is that after phi[i] gets set to non-zero and displayed to cout, it gets set to zero again in one of the later iterations through the inner loops.
If you do some tracing and check phi[i] just before updating you'll see that you often overwrite a non-zero element with zero.
Note: I have no idea what your code does, this is pure Sherlock Holmes reasoning.. if after the loops you find only 2 non-zero elements then the only logical consequence is that after updating something to non-zero later in the loop you update it to zero.
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
The nested for-loops using a, b, and c run for a combined 9 iterations with the same value of i. Since you overwrite phi[i] to a new value every time, you only retain the value from the last iteration where a, and c are all 1. If that last iteration happens to produce zero values, then phi[i] will have lots of zeroes. Perhaps you meant to do something like phi[i] += ... instead of phi[i] = ...?
I do suggest to replace the meat of the loop with something like
const boost::irange domain(-1,2);
for (int i: boost::irange(0, nmask)) for (int a: domain) for (int b: domain) for (int c: domain)
{
if (a==0 && b==0 && c==0)
continue;
//oneD26 is just (double) 1/26
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
if (phi[i]!=0)
{
//this gives expected results: 27 nonzero elements (including tvox)
cout << n << " " << i << " " << a << b << c << " " << phi[i] << endl;
}
}
Of course, for brevity I assume both boost/range.hpp and c++0x compiler. However, with trivial macro's you can achieve the same. That is without writing/using a proper combinations algorithm (why is that not in the standard, anyway).