-
A beginners problem.
Hello,
I have been beating my head against this problem for some time now, and figured I would see if i could get some fresh eyes, the code is:
Code:
int main(){
cout << "Enter as many words as you would like: ";
vector<string> Words;
string x;
while(cin >> x){
Words.push_back(x);
}
//How many words were entered
int i = 0;
int Count = Words.size();;
const int n = Words[i].size();
while(i != Count){
cout << n << endl;
++i;
}
return 0;
}
Pretty simple, just working no this functionality before i add what needs to be done with the concept. Right now it should be reading into a vector, using variable Count to count how many entries were made and uses this in the loop to determine when to stop.
As of right now it does stop, however, although variable 'n' is const it does rely upon i changing. I can COUT i within the while function to verify that i was actually counting up (yeah i got that desperate)..but for some reason the result of n never changes..for instance..:
Code:
[Spazmotic@localhost Chapter3]$ ./Exercise3-4
Enter as many words as you would like: a ab abb abbb
1111 <--- result
I do know that since it is scoped it and looping there's no way for it to back and read the n definition again...but any way to fix it is beyond me :(
I have tried declaring the variable 'n' right within the while loop but it Seg Faults as soon as i hit end of file..
Any suggestions / Road signs?
-
At the moment you declare the const variable n, its value is set and unchangeable. Just because you used the variable i in determining what to store in n at that point has no bearing in what n is later in the code as your loop increments i. n will not change because all it understands is that it holds a value. It doesn't understand how it got that value (the "equation" used to calculate it) and how to therefore magically alter itself based upon varying values of i.
-
HK_mp5,
That was an incredibly concise and helpful answer, thank you very much. I was under the assumtion that as there no actual value stored into 'n' but an equation, that every time 'n' it was called, it would run the equation. But the real way it works sounds much less like 'n' came from hogwarts :p
I have no idea why I thought defining a constant within a loop would be a good idea, and why I did not realize this would cause a problem.
Thank you again sir :)