Hi Tech gurus,
I am studying c++ using "Thinking in c++" now am in chapter 1 and solving the exercises , I have solved the last two questions
Q9 ) Create 3 vector <float> objects and fill the first two. write a for loop and that adds each corresponding elements of the first 2 vectors and puts the resultant in the third one . Display all 3.
#include<iostream>
#include<vector>
usingnamespace std;
int main()
{
vector <float> v;
int i;
float x;
cout << " enter 25 floating no.s"<<endl;
for (i=0;i<6;i++)
{
cin >> x;
v.push_back(x);
}
cout << " you just entered :" <<endl;
for (i=0;i<v.size();i++)
{
v[i] = v[i] * v[i] ;
cout << v[i] <<endl;
}
system("pause");
return 0;
}
Both of them working , but doubt is for multiplication it's giving proper result if I write like "v[i] = v[i] * v[i] " but for the above exercise if i write like v3[i] = v[i] + v2[i] (which I have commented the console stops while trying to print the result of the 3rd vector , but otherwise (as in the code) it gives correct result. Can someone tell me why so?
but doubt is for multiplication it's giving proper result if I write like "v[i] = v[i] * v[i]"
It will in your case.
Problem with commented out addition is that your v3 vector has 0 elements and things like v3[0] or v3[2] are illegal: you are accessing outside vector bounds. When you do push_back() you are increasing vector size by 1 (adding new element at the end).
If you do index access on empty vector program might not crash immideatly, but you can corrupt some memory that way. Also vector size will remain 0 and your loop will assume that vector does not have any elements.
In multiplication you are accessing already existing values and everything is fine.
just another doubt in another context below is the code for word count (not my code)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
1 2 3 4 5 6 7 8 9 10
int main() {
ifstream f("helloworld.cpp");
int nwords=0;
string word;
while (f >> word)
++nwords;
cout << "Number of words = " << nwords << endl;
}
I understand while (f >> word) doesn't recognize whitespace and counts the word (got cleared in my previous post) but how does it check for the end of file because in C we provide it manually. Kindly explain
When it tries to read past the ent of file, it fails. That sets stream in failed state. After that stream will be converted (via operator bool) to false and loop stops.