Why is there no error for this code - c++

According to Stroustrup Programming.. the below code should produce a range error. The error is in the last line i<v.size() instead of i<=v.size.
I ran the code and it outputs the contents of the vector including v[v.size] instead of throwing an exception. I am using CodeBlocks with mingw.
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
vector<int>v;
for (int x;cin>>x;) v.push_back(x);
for (int i=0;i<=v.size();i++) cout << "\nv[" << i << "]==" << v[i];
}

What error did you expect? There is no compilation error here, but there is a runtime error. When printing the read values it will always go one step too far. If you read 2 values it will print indexes 0, 1 and 2.
This can be fixed by changing i<=v.size() to i<v.size().
It is very common in indexed for-loops to always follow the following pattern; then you know you'll never be wrong:
for (int i = 0; i < count; i++) {
...
}

Related

I have a problem with reading from a file

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream file, save_file;
vector<string> words;
for (int i = 0; i < 1000; i++)
file >> words[i];
cout << words[0];
return 0;
}
I want to save these words in a vector, but I can't. I have a message: zad1.exe is already runing! Please close it first to compile successfully! I don;t know why.
Here is my solution:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main()
{
std::fstream file("test.txt"), save_file;
std::vector<std::string> words;
std::string line;
for (int i = 0; i < 1000; i++){
file >> line;
words.push_back(line);
}
std::cout << words[0];
return 0;
}
Instead of test.txt write your file path
On some operating systems you cannot write to a file if that file is a running program. That is what the error message is telling you. You are creating a program called zad1.exe and it is currently running so you cannot create a new version of zad1.exe until you stop the version that is already running.
Are you working on Windows? If so then use the task manager to kill any versions of zad1.exe that you can see.
Plus you have many problems with the code as pointed out in the comments above. But the first task is to kill those running programs.

Trying to understand more about bitset in c++

I was trying to understand more about using bitset to convert a string into binary then transfer it into another string rather then just cout straight. I will always receive an exception error "Unhandled exception at 0x773D3DB2 C++ exception: std::invalid_argument at memory location 0x006FF800.
" using visual studio 2017 may i know why?
#include <string>
#include <bitset>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
std::string hello = "C";
std::string yellow;
for (auto character : hello)
{
yellow += std::bitset<7>(hello).to_string();
cout << yellow;
return 0;
}
}
You are guilty of not having warnings enabled for your compiler, or using a compiler not capable of warning you that the variable character is not used in your loop.
Change
yellow += std::bitset<7>(hello).to_string();
to
yellow += std::bitset<7>(character).to_string();
Output:
1000011
Also, note that you don't actually loop, because your loop returns on its first iteration. I assume that your code example has gone through several iterations of trial & error by this point...

C++ - Looping through vector runs infinitely

I'm new to C++, came from Java (started learning yesterday).
I'm trying to loop over the elements of a vector. For some reason when I do this, it endlessly outputs empty lines.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string expression = "5+4";
std::vector<char> characters(expression.begin(), expression.end());
for (char c : characters) {
std::cout << c << std::endl;
}
}
I keep running into this problem, I have no clue why it is doing this.
I tried searching if other people had this problem, but I couldn't find any questions about it or answers... what am I doing wrong?
EDIT:
I'm using MinGW
GIF or it didn't happen
I'm not an expert in CPP, but i assume your code is inserting string to the vector and iterate through the vector, if so, heres the code :
#include <iostream>
#include <string>
#include <vector>
using namespace std; //i add this line to remove the "std" in every line
int main()
{
string expression = "5+4";
vector <char> characters(expression.begin(), expression.end());
for (int i=0; i< characters.size(); i++)
{
cout << characters[i] << endl;
}
}
An explanation that i can tell you is, you do not printing the vectors with its index so it'll have some bug also the looping i use i think more clear to see.

Array of Ofstream in c++

I want 41 output files to use in my project to write text on them. first create a string array list to name those output files then I tried to define an array of ofstream objects and use list to name them, but I get this error that 'outfile' cannot be used as a function. Below is my code:
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std ;
int main ()
{
string list [41];
int i=1;
ofstream *outFile = new ofstream [41];
for (i=1;i<=41 ;i++)
{
stringstream sstm;
sstm << "subnode" << i;
list[i] = sstm.str();
}
for (i=0;i<=41;i++)
outFile[i] (list[i].c_str());
i=1;
for (i=1;i<=41;i++)
cout << list[i] << endl;
return 0;
}
See below for the following fixes:
don't use new unless you have to (you were leaking all files and not properly destructing them will lead to lost data; ofstreams might not be flushed if you don't close them properly, and the pending output buffer will be lost)
Use proper array indexing (starting from 0!)
Call .open(...) on a default-constructed ofstream to open a file
Recommendations:
I'd recommend against using namespace std; (not changed below)
I recommend reusing the stringstream. This is is good practice
Prefer to use C++-style loop index variables (for (int i = ....). This prevents surprises from i having excess scope.
In fact, get with the times and use ranged for
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream outFile[41];
stringstream sstm;
for (int i=0;i<41 ;i++)
{
sstm.str("");
sstm << "subnode" << i;
outFile[i].open(sstm.str());
}
for (auto& o:outFile)
cout << std::boolalpha << o.good() << endl;
}
You can not call the constructor as you do. Try calling outFile[i].open(list[i].c_str()). Note the 'open'.

the output is not what i typed.It is --> (畳慨汩朠灵慴찀쳌쳌쳌)

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
char x[20];
cout << "enter something\n";
cin.getline(x,20);
ofstream o("d:/tester.txt");
//o.write( (char*)&x , sizeof(x) );
for(int i = 0 ; i<=19 ; i++ ) {
o.put(x[i]);
}
}
I am not getting that output in the file the one which i enter during program . for eg. the output is 畳慨汩朠灵慴찀쳌쳌쳌 on writing suhail gupta.
What is the problem with the code ? Even when i use o.write( (char*)&x , sizeof(x) ); (the commented statement) i get the same output.
What is the reason?
Your program involves undefined behavior. The x array is not fully initialized and you read from the uninitialized indices. Besides, you always write 20 bytes, independent of what you read from the user.
I guess you use some text editor like Notepad. The latter has bugs when trying to guess the encoding. It appears that it guesses the file is UTF16 and displays 20/2 == 10 characters instead.
To solve the problem, store to the file exactly the number of characters entered by the user. Use std::string to make it easier.
Edit: The C++ way:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
cout << "enter something\n";
getline(cin, x);
ofstream o("d:/tester.txt");
o << x;
}