Crash when using ofstream - c++

I have a problem with the following code. I would like to write out data into different files in a loop. But when I instantiate ofstreams in a loop, my program silently crashes. I've boiled the code down, so that it doesn't do anything useful. It just demonstrates the behavior that I cannot explain:
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char* argv[])
{
ofstream test_a("a.json");
cout << "test a" << endl;
ofstream test_b("b.json");
cout << "test b" << endl;
for (int idx = 0; idx < 3; idx++)
{
cout << "test " << idx << endl;
ofstream test("test_" + to_string(idx) + ".json");
}
return 0;
}
This is the output:
test a
test b
test 0
Nothing else, no error, nothing.
The first two ofstreams are apparently fine, but the loop stops somewhere after the cout. I am using Windows 10 and mingw:
gcc version 8.1.0 (x86_64-win32-seh-rev0, Built by MinGW-W64 project)

Thanks to the helpful comments I found that I linked a std library that must have been from an older version of my compiler. I fixed that and now it works.

Related

VS code set up for c++

I am new in VS code. I wrote a C++ code like one below. but unfortunately in the terminal or output panel I cannot get both of the string and variable value. in the terminal only variable's inputted value is showing. How to fix this?
#include <bits/stdc++.h>
int main()
{
int slices;
std::cin >> slices;
std::cout << "You got " << slices << " of pizzas" << std::endl;
return 0;
}

Why does the function find of C++ stl string sometimes go wrong sometime go right?

I am trying to do some file reading with C++ in Ubuntu 16.04 (GCC&G++ 5.4 and CMake 3.5.1).
The test file (named 123.txt) have only a line words just like this:
Reprojection error: avg = 0.110258 max = 0.491361
I just want to get the avg error and max error. My method is to get a line and put them into a std::string
and use string::find. My codes are very easy just like this:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
FILE *fp = fopen("123.txt", "r");
char tmp[60];
string str;
fgets(tmp, size_t(tmp), fp);
fclose(fp);
cout << tmp << endl;
str = tmp;
cout << str.size() << endl;
size_t avg = str.find("avg");
size_t max = str.find("max");
cout << avg << endl;
cout << max << endl;
}
I can use g++ to compile it successfully. But I meet a strange issue.
When I first run it in the command, it will get the right result:
Reprojection error: avg = 0.110258 max = 0.491361
52
20
37
If I run codes again, it will go wrong sometimes just like this:
p
2
18446744073709551615
18446744073709551615
The "p" is a disorderly code which can not be shown correctly in the command. I am not good at C++ and feel confused about it. Is there someone who can say something? Thank you!
The expression
fgets(tmp, size_t(tmp), fp);
is ill-formed, size_t(tmp) will not work as you expect, you need sizeof(tmp).
The 52 value you get is because fgets consumes the \n character and this is counted too, actually the string has 51 characters counting with spaces.
That said, in this case you can use better C++ tools to replace the C ones you are using, fopen can be replaced by using the fstream library, fgets can be replaced by getline.
Something like:
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream fp("123.txt"); //C++ filestream
if (fp.is_open()) {//check for file opening errors
std::string str;
std::getline(fp, str); //C++ read from file
fp.close();
std::cout << str << std::endl;
std::cout << str.size() << std::endl;
size_t avg = str.find("avg");
size_t max = str.find("max");
std::cout << avg << std::endl;
std::cout << max << std::endl;
}
else{
std::cerr << "Couldn't open file";
}
}
Note that I dind't use using namespace std;, this is for a reason, it's not a good practice, you can check this thread for more details.

Cout does not work on my other turbo c++ complier

Hello guys i am beginner on the language c++
i was trying to run this code below on my ide"codeblocks" and it works
https://www.youtube.com/watch?v=vLnPwxZdW4Y (link for the tutorial that following )
#include <iostream>
using namespace std;
int main()
{
string charactername = "arnold";
int characterage;
characterage = 10;
cout << "Hello my name is" << charactername<< endl;
cout << "i am " << characterage << endl;
return 0;
}
this code does not work on my other compiler running on dosbox ? any ideas why ?
I suggest you stop using Turbo C++ as it is a very outdated and a discontinued compiler. However, if you don't have the option of using new compilers (I had the same issue as I studied C++ at school), you will have to make the following changes:
using namespace std; cannot be used in Turbo C++. You will have to remove that and replace #include<iostream> with #include<iostream.h>
Data-type string cannot be used in Turbo C++. You will have to declare a character array instead.
You will have to use #include<stdio.h> and the function puts(); to display the character array in case of Turbo C++. Alternatively you can use a loop-statement.
This will be your final code:
#include <iostream.h>
#include <stdio.h>
int main()
{
char charactername[] = "arnold";
int characterage;
characterage = 10;
cout << "Hello my name is ";
puts(charactername);
cout << "i am " << characterage << endl;
return 0;
}
Note: The puts(); function automatically puts the cursor on the next line. So you don't need to use endl;
Or, if you want to use a loop-statement to display the character array
#include <iostream.h>
int main()
{
char charactername[] = "arnold";
int characterage;
characterage = 10;
cout << "Hello my name is ";
int i=0;
while(charactername[i]!='\0') {
cout<<charactername[i];
i++;
}
cout<<endl;
cout << "i am " << characterage << endl;
return 0;
}
'\0' is the last element of the character array. So as long as the loop does not reach the last element, it will print the character array.
a[] = "arnold"; basically means an array is created like this: a[0]='a', a[1]='r', a[2]='n',.... a[5]='d', a[6]='\0'.
Alternatively, if you use cout << charactername; instead of the while loop, it will print the whole name. (This is only in the case of a string variable (character array), for an integer array or any other array you will need the while loop)

Skip'ing on a Source does not work as expected

I use Crypto++ 5.6.3 and iI need the FileSource Skip(...) function. Unfortunately this function does nothing!
Here is a example for this function.
string filename = ...;
string str;
FileSource file(filename, false, new HexEncoder(new StringSink(str)));
file.Skip(24);
file.PumpAll();
Can somebody help me?
I use Crypto++ 5.6.3 and iI need the FileSource "skip(...) function. Unfortunately this function does nothing!
I was able to duplicate this using strings under Master, 5.6.3, and 5.6.2 on OS X 10.8.5 and Ubuntu 14.04.
$ cat test.cxx
#include <string>
#include <iostream>
using namespace std;
#include <filters.h>
#include <hex.h>
using namespace CryptoPP;
int main(int argc, char* argv[])
{
string str1, str2;
HexEncoder enc(new StringSink(str1));
for(unsigned int i=0; i < 32; i++)
enc.Put((byte)i);
enc.MessageEnd();
cout << "str1: " << str1 <<endl;
StringSource ss(str1, false, new StringSink(str2));
ss.Skip(10);
ss.PumpAll();
cout << "str2: " << str2 << endl;
return 0;
}
And:
$ ./test.exe
str1: 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
str2: 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
Crypto++ 5.6.2 is significant because it was the last version Wei worked on before turning the library over to the community. An issue in 5.6.2 is just a latent bug and we encounter them on occasion, just like any other project. ("Wei" bugs are actually kind of rare, and they are closer to "Knuth" bugs in his Art of Computer Programming).
If its a 5.6.3 and above problem, then it means the community broke it. If the community broke it, then we need to perform a post-mortem and analyze how/why we managed to break something that used to work.
Here's the bug report for the library: Issue 248: Skip'ing on a Source does not work. We are trying to determine if its a bug; and if so, then how to proceed.
EDIT 1: I was able to investigate the issue a little more. You can read the analysis at Comment 242890863. The short of it is, Skip is used to discard bytes on an output buffer (an AttachedTransformation()), so things are somewhat working as expected. However, there's nothing intuitive about Skip not working on the Source, and only working on the attached Filter (q.v., we're here).
I also asked for some feedback on the mailing list at Issue 248: Skip'ing on a Source does not work. DB and WD spotted it right away - its a design issue in the library.
Here's the workaround you can use for the moment. Effectively, you Pump() into a null Filter which discards the input as expected. Then you attach the real filter chain to handle the real processing.
#include <string>
#include <iostream>
using namespace std;
#include <filters.h>
#include <hex.h>
using namespace CryptoPP;
int main(int argc, char* argv[])
{
string str1, str2;
HexEncoder enc(new StringSink(str1));
for(unsigned int i=0; i < 32; i++)
enc.Put((byte)i);
enc.MessageEnd();
cout << "str1: " << str1 <<endl;
// 'ss' has a NULL AttachedTransformation()
StringSource ss(str1, false);
ss.Pump(10);
// Attach the real filter chain to 'ss'
ss.Attach(new StringSink(str2));
ss.PumpAll();
cout << "str2: " << str2 << endl;
return 0;
}
It produces the expected output:
$ ./test.exe
str1: 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
str2: 05060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
In your sample program, I believe the workaround would be:
FileSource file(filename, false);
file.Pump(24);
file.Attach(new HexEncoder(new StringSink(str)));
file.PumpAll();
EDIT 2: Here's a slightly more verbose way to achieve the work around (thanks DB). It stresses the point that bytes are being discarded. TheBitBucket() is simply a discard filter, and it serves the same purpose as a null AttachedTransformation().
int main(int argc, char* argv[])
{
string str1, str2;
HexEncoder enc(new StringSink(str1));
for(unsigned int i=0; i < 32; i++)
enc.Put((byte)i);
enc.MessageEnd();
cout << "str1: " << str1 <<endl;
StringSource ss(str1, false, new Redirector(TheBitBucket()));
ss.Pump(10);
ss.Detach(new StringSink(str2));
ss.PumpAll();
cout << "str2: " << str2 << endl;
return 0;
}
There's another subtle difference in the program above: It calls Detach, which free's the former filter chain. If you called Attach, then the former chain would be detached, returned to the caller but not free'd.

source code of linked directory is not read?

I just started using Microsoft Visual Studio 2010 for compiling my C++ code.
I have a project that is linked to another project called firmlib. To that end, I have linked the header files and libraries as described here:
http://www.steptools.com/support/stdev_docs/help/settings_vc10.html#header
In the new main that I wrote I call a method called readFromFile of the class Curve, as follows:
#include "stdafx.h"
#include <iostream>
#include "curve.h"
int _tmain(int argc, _TCHAR* argv[])
{
unsigned long n;
Curve discountCurve;
discountCurve.readCurve("fileName");
std::cout << "Give a natural number: " << endl;
std::cin >> n;
std::cout << "The faculty of " << n << " equals " << faculty(n) << ".\n";
return 0;
}
referring to the following method declaration (in Curve.h)
void readCurve(const char * filename){}
and implementation (in Curve.cpp) (I deleted some parts that are irrelevant for this post):
void Curve::readCurve(const char * filename){
cout << "Hi. This is the function Curve::readCurveat work.") << endl;
ifstream data;
marketData.open(filename);
marketData.close;
}
I built in the stream to the console in order to make sure that the source code is actually compiled. However, nothing is happening! So apparently the source code is not compiled.
Can anyone tell me what is going wrong here? I am puzzled ...
Thanks!