Build error on very simple code using C++ 20 Visual Studio 2022 64bit version 17.11.3
Seems to be getting error in the compiler code base. As far as I can tell the code is fine. I know about not using the using this is just learning code at this time.
#include <cstdio>
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using std::vector;
vector<int> read_input() {
std::string line;
std::ifstream fp;
vector<int> data;
int word;
fp.open("input.txt");
if (fp) {
while (getline(fp, line, 'n')) {
vector<int> tempdata;
std::istringstream ss(line);
while (ss >> word) {
tempdata.push_back(word);
}
data.emplace_back(tempdata);
}
fp.close();
}
else
perror("File opening failed");
return data;
}
Data in input.txt
43 32 21 23 43 98 90 65 53 42 69 79 82 7 1 63 64 90 87 96 4 55 3 7 2 1 67 89 543
567 985 34 975 890 4567 23 33 9 56 345 9865
3
You are trying to insert a vector<int>
into a vector<int>
. That does not work. A vector<int>
is not convertible to int
.
You can use vector::insert
with iterators from tempdata
instead. This tells it to insert it at the end of data
:
data.insert(data.end(), tempdata.begin(), tempdata.end());
// ^^^^^^^^^^
// insert before this
Since C++23, you can also use vector::insert_range
:
data.insert_range(data.end(), tempdata);
Since you are flattening the data, making it into a 1d vector of int
, you could simplify it using istream_iterator
s:
#include <cstdio>
#include <fstream>
#include <iterator>
#include <vector>
std::vector<int> read_input() {
if (std::ifstream fp("input.txt"); fp) {
return {std::istream_iterator<int>(fp),
std::istream_iterator<int>{}};
}
std::perror("File opening failed");
return {};
}
If you actually want one vector<int>
per line in the file, you need to make the vector
that you insert into a vector<vector<int>>
(and modify the return value of read_input
accordingly). Here’s a full example of that:
#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::vector<int>> read_input() {
std::vector<std::vector<int>> data;
if (std::ifstream fp("input.txt"); fp) {
std::string line;
while (std::getline(fp, line, 'n')) {
std::istringstream ss(line);
// default construct a vector<int> in data
// and get a reference to it:
auto& current_vec_int = data.emplace_back();
int word;
while (ss >> word) {
current_vec_int.emplace_back(word);
}
}
// fp.close(); // no need, it closes automatically
} else {
std::perror("File opening failed");
}
return data;
}
int main() {
auto input = read_input();
for (auto& vec_int : input) {
for (int val : vec_int) {
std::cout << val << 'n';
}
std::cout << 'n';
}
}
Or using istream_iterator
s:
while (std::getline(fp, line, 'n')) {
std::istringstream ss(line);
data.emplace_back(std::istream_iterator<int>(ss),
std::istream_iterator<int>{});
}
4