freopen and cout creating internal error - c++

I'm trying to read and write some files, but i get "ERROR C1001, internal error happened in compiler" every time i try to std::cout something to my output.out file.
Why ?
(i used _CRT_SECURE_NO_WARNINGS in preprocesssor definition to be able to use freopen())
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <deque>
#include <array>
#include <vector>
freopen("C:\\somepath\\input.in", "r", stdin);
freopen("C:\\somepath\\output.out", "w", stdout);
int t;
std::cin >> t;
std::cout << t << std::endl;
for (int i = 0; i < t; i++)
{
int n;
std::cin >> n;
std::cout << t << std::endl;
std::vector <int> x, h;
x.resize(n);
h.resize(n);
for(int j=0;j<n;j++)
{
std::cin >> x[j] >> h[j];
std::cout<< x[j] << h[j] << std::endl;
}
}
EDIT : as Nighteen said, i had some errors in my code (n++, no vector resizing, now corrected)
But the bug, still there in some way :
The code is compiling in this state, but as soon as i try put cout a string, the same probleme appears
like adding <<" " in my std::cout<< x[j] << h[j] << std::endl;
in the std::cout<< x[j] <<" "<< h[j] << std::endl;

The code compiles fine in MSVC 15.5.2 assuming you put the code in a main block. Proof here.
Even though the compilation is OK, the code seems not to work out as it should. First of all, you can't std::cin >> x[j] >> h[j];. Create a temporary variable to store the input and then push it back into the vector:
int input1, input2;
std::cin >> input1 >> input2;
x.push_back(input1);
h.push_back(input2);
You should also note that this loop for (int j = 0; j < n; n++) never ends. The variable j should be increasing, not n. Whatever you are trying to achieve, this does not seem to be the way.

std::cout is a std::ostream used for outputting to the console. For outputting to files, used the classes std::ifstream and std::ofstream. Use the following syntax:
std::ifstream [ifstream_name](constructor parameters);
[ifstream_name] >> [container to store file contents];
std::ofstream [ofstream name](constructor parameters);
[ofstream_name] << [contents to write to file];

Related

How should I read words and put them into vectors in C++?

So the user needs to input the number of words and then input the words themselves. How should I read these words and put them into a vector ?
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main(){
int n;
vector<string>words;
string word;
cin >> n;
for (int i = 1; i <= n; i++){
cin >> word;
words.push_back(word);
}
cout << words;
}
I've tried this but when I run it it gives me an error saying "no match for 'operator<<' " , it's something to do with cout << words; Could any of you please explain this error as well ?
The error is coming not from reading the words, but from printing them on this line:
cout << words;
There is no overload of operator<< for std::cout that takes a std::vector<std::string>. You need to write the loop yourself:
for (auto const & word : words)
std::cout << word << " ";
Also, please don't use using namespace std;. And the correct header for std::string is <string>, not <string.h>.
You're going to need to loop through the vector and display the words one by one.
This means using:
for(int i = 0; i < words.size(); i++)
cout << words[i] << endl;
It's a syntax error to cout a vector like that.

printing weird symbols to output file, c++

I am writing a code that reads an input file of numbers, sorts them in ascending order, and prints them to output. The only thing printed to output is some really freaky symbols.
Here is my code
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i, y, temp, num[20];
char file_nameI[21], file_nameO[21];
ofstream outfile;
ifstream infile;
cout << "Please enter name of input file: ";
cin >> file_nameI;
infile.open(file_nameI);
if (!infile)
{
cout << "Could not open input file \n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> file_nameO;
outfile.open(file_nameO);
if (!outfile)
{
cout << "Could not open output file \n";
return 0;
}
for (i = 0; i < 20; i++)
{
y = i + 1;
while (y < 5)
{
if (num[i] > num[y]) //Correction3
{
infile >> temp;
temp = num[i];
num[i] = num[y];
num[y] = temp;
//y++; //Correction4
}
y++;
}
}
for (i = 0; i < 5; i++)
outfile << "num[i]:" << num[i] << "\n";
return 0;
}
Here is my input
6 7 9 0 40
Here is the output
 „Ô,üþ 54
H|À°ÀzY „Ô,üþ 0
Problems with your code are already mentioned in the comments but again:
First problem is uninitialized elements of num[20] - elements of num have indeterminate values so accessing any of them triggers undefined behavior. You should first read them from the file or at least initialize them to some default value.
The part of code that should most likely do the sorting is just completely wrong. If you'd like to implement your own function for sorting, you can pick up some well-known algorithm like e.g. quicksort - but C++ Standard Library already provides sorting function - std::sort.
Besides obvious mistakes:
You are using char[] - in C++ it's almost always better to use std::string.
Your static array can only store 20 values and you are reading those from a file. You can use std::vector which can grow when you add more elements than its current capacity. It also automatically fixes the problem with uninitialized elements of num[20].
As mentioned in the comments you can organize your code and improve readability by splitting it into functions.
Here you've got it quickly rewritten. This code uses std::string instead of char[], std::vector to store the numbers and std::sort. If there is something you don't understand here, read SO documentation:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> read_file(ifstream& in_file)
{
vector<int> vec;
int value;
while (in_file >> value)
{
vec.push_back(value);
}
return vec;
}
void write_file(ofstream& out_file, const vector<int>& values)
{
for (size_t i = 0; i < values.size(); ++i)
out_file << "value #" << i << ": " << values[i] << '\n';
}
int main()
{
string input_filename, output_filename;
ofstream out_file;
ifstream in_file;
cout << "Please enter name of input file: ";
cin >> input_filename;
in_file.open(input_filename);
if (!in_file)
{
cout << "Could not open input file\n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> output_filename;
out_file.open(output_filename);
if (!out_file)
{
cout << "Could not open output file\n";
return 0;
}
auto numbers = read_file(in_file);
sort(begin(numbers), end(numbers));
write_file(out_file, numbers);
return 0;
}
You might forgot to store values in num array. Just update your code as follows and it will work.
infile.open(file_nameI);
if (!infile){
cout << "Could not open input file \n";
return 0;
} else{
i = 0;
while (infile >> num[i]){
i++;
}
}

C++ Making a char array recognise spaces upon input

I'm trying to make a program that flips the words you input. The problem comes when I try to write the word and it asks twice for the input:
cin >> Arr >> myStr;
It is logical that it ask twice but everytime I try to use getline the compiler gives out an error (and even if it worked I have to give the input twice) and I need it to include spaces in the character array.
Here is my full code:
#include <iostream>
#include <string>
using namespace std;
string myStr;
string newVal;
int i;
int main()
{
char Arr[i];
cout << "Enter: ";
cin >> Arr >> myStr;
for (i = myStr.length(); i >= 0; i--)
{
cout << Arr[i];
}
cout << endl;
return 0;
}
The loop works.
The first problem can be corrected by achieving the proper use of getline.
The second one, I have got no idea (use a single input to assign two variables).
Thanks in advance, and I apologise if this is too much of a ridiculous question.
Maybe you can try to have a look to this solution that it's more C++ style than yours:
#include <iostream>
#include <string>
int main() {
std::string myStr;
std::cout << "Please give me a string: ";
if(std::getline(std::cin, myStr)) {
for(std::string::reverse_iterator it = myStr.rbegin();
it != myStr.rend();
++it) {
std::cout << *it;
}
std::cout << std::endl;
}
}
I suggest to you to use always std::string in C++ because has all the methods and function that you could need. So don't waste your time with char array like you do in C.
Here it is, as I said. I was digging around and came up with this:
#include <iostream>
#include <string>
using namespace std;
string myStr;
int i;
int main()
{
cout << "Enter: ";
getline (cin, myStr);
i = myStr.size();
cout << i << endl;
char Arr[i];
for (int a = 0; a <= i; a++)
{
Arr[a] = myStr[a];
}
for (i; i >= 0; i--)
{
cout << Arr[i];
}
return 0;
}
I did not know string contents could also have array-like behaviour. Test it out! Works like a charm (as far as tested).
The way I formatted the code it takes no more than 27 lines of code.
Thanks everyone involved, you helped me a lot.
P.S: Couldn't answer before, I can't do it soon enough with my reputation.

How to read txt file into vector and cout the file?

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> temp;
ifstream infile;
infile.open("numbers");
if (infile.fail())
{
cout << "Could not open file numbers." << "\n";
return 1;
}
int data;
infile >> data;
while (!infile.eof()) {
temp.push_back(data);
infile >> data;
}
cout << data << " " << endl;
}
I am simply trying to cout all the numbers from the text file "numbers" using a vector.
15
10
32
24
50
60
25
My experience is pretty much nil, and some guidance on why this fails to open would be very helpful.
Your code isn't working because you haven't attempted to print anything from the vector?
How do I print a vector?
Well first you have to understand how not to print a vector. The last line in your code, particularly this one:
cout << data << " " << endl;
is only printing out the last integer from the text file. In the loop where you performed the input, infile >> data overwrote each previous value of data and assigned it to the currently read value from the file. The result is that when the loop finishes, data will be equal to the last read value, particularly 25 looking at your file.
There's no overload for operator<<() that will allow you to do something like cout << temp, though you can implement one yourself. There exist several ways to print a vector, the easiest being a simple loop:
for (unsigned i = 0; i < temp.size(); ++i)
std::cout << temp[i] << " ";
Bonus: A faster way to print all the integers would be to print data from inside the loop. There's also the answer #KerrekSB made.
Your code is fine but you're printing the wrong thing.
Change the bottom of main to this
int data;
while (infile >> data) {
temp.push_back(data);
}
for( vector<int>::iterator i = temp.begin(); i != temp.end(); i++) {
cout << *i << endl;
}
*Edited after reading the suggested dup.
Try this:
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream infile("data.txt");
if (!infile) { /* error opening file */ }
for (int n : std::vector<int>(std::istream_iterator<int>(infile), {}))
{
std::cout << n << '\n';
}
}
Of course you don't need the vector if you just want to process the numbers:
for (std::istream_iterator<int> it(infile), end; it != end; ++it)
{
std::cout << *it << '\n';
}

the program ignores second loop

my program ignores second loop and I can't fill vector v2
vector<int> v1;
vector<int> v2;
int elem1,elem2;
cout<<"Insert v1: ";
while(cin>>elem1){
v1.push_back(elem1);
}
cout<<"Insert v2: ";
while(cin>>elem2){
v2.push_back(elem2);
}
cin keeps going until all output is done, your 2nd loop is never gonna get hit unless you break from your first loop somehow. I would recommend you have some sort of exit condition on the first loop (such as some input marker like 'DONE' or something and once you read that you should break).
I'm guessing that you were expecting the first loop to end when you hit enter or something. but that's not what you coded. You coded 'fill up v1 until there is no input left', so it's not surprising that nothing ever gets put in v2.
Perhaps you could try the following, this reads one line, and put the contents in v1, it then reads a second line and puts the contents in v2. It uses getline to read a single line of text, then put that line into a string stream where you can read from one number at a time.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
void fill_vector_from_one_line(vector<int>& v)
{
string str;
if (getline(cin, str))
{
istringstream iss(str);
int elem;
while (iss >> elem)
v.push_back(elem);
}
}
int main()
{
cout << "Insert v1: ";
fill_vector_from_one_line(v1);
cout << "Insert v2: ";
fill_vector_from_one_line(v2);
}
Apologies for any errors, I haven't checked this.
Reset standard input. See below.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v1;
std::vector<int> v2;
int elem;
std::cout << "Insert v1: ";
while (std::cin >> elem) {
v1.push_back (elem);
}
// Reset std::cin.
std::cin.clear();
std::cin.seekg(0, std::ios::beg);
std::cout << "Insert v2: ";
while (std::cin >> elem) {
v2.push_back (elem);
}
// Just to show that it works.
std::cout << "\nv1 elements:\n";
for (unsigned int ii = 0; ii < v1.size(); ++ii) {
std::cout << "v1[" << ii << "] = " << v1[ii] << "\n";
}
std::cout << "\nv2 elements:\n";
for (unsigned int ii = 0; ii < v2.size(); ++ii) {
std::cout << "v2[" << ii << "] = " << v2[ii] << "\n";
}
return 0;
}
Note that the std::cin.clear(); std:cin.seekg(); calls will have different behaviors depending on the nature of std::cin.
If std::cin is tied to the terminal it will have exactly the behavior that the OP is seeking.
If std::cin is reading from a file, vector v2 will be a carbon copy of vector v1.
If std::cin is reading from a pipe, vector v2 will be empty. You can't seekg() on a pipeline.