vector<string> names;
// Read names from file book.txt
ifstream in("movie.txt");
if (!in.is_open())
cout << "Unable to open file\n";
string word;
while (getline(in, word))
names.push_back(word);
int pos(0), i(0), j(0);
string temp;
for (size_t i = 0; i < names.size(); i++)
{
j = i;
while (j >= 0 && names[j] < names[j - 1])
{
temp = names[j];
names[j] = names[j - 1];
names[j - 1] = temp;
j--;
}
}
// Loop to print names
for (size_t i = 0; i < names.size(); i++)
cout << names[i] << '\n';
Not sure where the error is coming from as it still runs, but as i try
and execute the file it says "Debug assertion error." Any help?
If you want to read the names then try this it works
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char **argv)
{
vector<string> names;
ifstream in("movies.txt");
if (!in.is_open())
cout << "Unable to open file\n";
string word;
while (getline(in, word))
names.push_back(word);
for (auto i : names)
cout << i << '\n';
return 0;
}
Related
Like the title says I'm trying to read an unknown number of integers from a file and place them in a 2d array.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream f;int i,j,n,a[20][20];char ch;
i=0;j=0;n=0;
f.open("array.txt", ios::in);
while(!f.eof())
{
i++;
n++;
do
{
f>>a[i][j];
j++;
f>>ch;
}
while(ch!='\n');
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cout<<a[i][j]<<endl;
cout<<endl;
}
return 0;
}
and my "array.txt" file :
1 1 1
2 2 2
3 3 3
After compiling the program, it prints this
As your input file is line oriented, you should use getline (C++ equivalent or C fgets) to read a line, then an istringstream to parse the line into integers. And as you do not know a priori the size, you should use vectors, and consistently control that all lines have same size, and that the number of lines is the same as the number of columns.
Last but not least, you should test eof immediately after a read and not on beginning of loop.
Code becomes:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
fstream f;
int i=0, j=0, n=0;
string line;
vector<vector<int>> a;
f.open("array.txt", ios::in);
for(;;)
{
std::getline(f, line);
if (! f) break; // test eof after read
a.push_back(vector<int>());
std::istringstream fline(line);
j = 0;
for(;;) {
int val;
fline >> val;
if (!fline) break;
a[i].push_back(val);
j++;
}
i++;
if (n == 0) n = j;
else if (n != j) {
cerr << "Error line " << i << " - " << j << " values instead of " << n << endl;
}
}
if (i != n) {
cerr << "Error " << i << " lines instead of " << n << endl;
}
for(vector<vector<int>>::const_iterator it = a.begin(); it != a.end(); it++) {
for (vector<int>::const_iterator jt = it->begin(); jt != it->end(); jt++) {
cout << " " << *jt;
}
cout << endl;
}
return 0;
}
You may want to look into using a vector so you can have a dynamic array.
Try:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
fstream f;
int i, j, n, a[20][20];
string buf;
i = 0;
j = 0;
n = 0;
f.open("array.txt", ios::in);
while (1) {
getline(f, buf);
if (f.eof()) break;
stringstream buf_stream(buf);
j = 0;
do {
buf_stream >> a[i][j];
j++;
} while (!buf_stream.eof());
i++;
n++;
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Also, if you really want to read arbitrarily large arrays, then you should use std::vector or some such other container, not raw arrays.
Hi all i have a file i'm trying to read into a vector array.
I've checked a few other post that got me as far as i did.
I keep running into an error where it's not allowing me to insert my string using the put_back() function. I keep getting a char error.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using std::vector;
using namespace std;
string outPutFileName;
vector<vector<string> > array2D;
#define HEIGHT 32
#define WIDTH 9
int main() {
string x;
string line;
string filename;
ifstream infile;
infile.open("file.txt");
if (infile.fail()) {
cerr << " The file you are trying to access cannot be found or opened";
exit(1);
}
array2D.resize(HEIGHT);
for (int i = 0; i < HEIGHT; ++i) {
array2D[i].resize(WIDTH);
}
while (getline(infile, line)) {
istringstream streamA(line);
while (streamA >> x) {
for (int row = 0; row < HEIGHT; row++) {
for (int col= 0; col < WIDTH; col++) {
array2D[row][col].push_back(x);
col++;
}
row++;
}
}
}
for (int i = 0; i <HEIGHT; i++) {
for (int j = 0; j <WIDTH; j++) {
cout << array2D[i][j] << " ";
}
cout << endl;
}
return 0;
}
The type of array2D[row][col] is std::string, you are attempting to call push_back on that rather than one of the vectors. You probably meant:
array2D[row][col] = x;
Thanks for you help i found a solution.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using std::vector;
using namespace std;
string outPutFileName;
vector<vector<string> > array2D;
#define HEIGHT 32
#define WIDTH 9
int main() {
string x;
string line;
string filename;
ifstream infile;
infile.open("file.txt");
//error check
if (infile.fail()) {
cerr << " The file you are trying to access cannot be found or opened";
exit(1);
}
array2D.resize(HEIGHT);
for (int i = 0; i < HEIGHT; ++i) {
array2D[i].resize(WIDTH);
}
int row;
while (getline(infile, line)) {
istringstream streamA(line);
int col = 0;
while (streamA >> x) {
array2D[row][col] = x;
col++; // Note: This might go out of bounds
}
row++; // Note: This might go out of bounds
}
for (int i = 0; i <HEIGHT; i++) {
for (int j = 0; j <WIDTH; j++) {
cout << array2D[i][j] << " ";
}
cout << endl;
}
return 0;
}
I've been working on this program for a very long time now and I think I'm close to being done. However, my code is outputting something strange and I cannot find the issue.
Expected output:
This is a happy tESt to check if my reader works!
An happy alligator was AT tHe happy park and a happy a cow blew its nose in a happy scarf. are you an happy Octagon THe
Actual output:
This is a tE happySt to check if my reader works!
a happy
THe Happy
How can I make the following code behave as I expect?
#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>
#include <locale>
using namespace std;
void
usage(char *progname, string msg){
cerr << "Error: " << msg << endl;
cerr << "Usage is: " << progname << " [filename]" << endl;
cerr << " specifying filename reads from that file; no filename reads standard input" << endl;
}
string capitalization(string word,string adj){
for(int i = 0; i <= word.length(); i++){
if(isupper(word[i])){
for(int j = 0; j <= adj.length(); j++){
adj[j] = toupper(adj[j]);
return adj;
}
}
else if(isupper(word[0])){
for(int j = 0; j <= adj.length(); j++){
adj[j] = tolower(adj[j]);
return adj;
}
}
else{
for(int j = 0; j <= adj.length(); j++){
adj[j] = tolower(adj[j]);
return adj;
}
}
}
}
int main(int argc, char *argv[]){
string adj;
string file;
cin >> adj;
cin >> file;
string line;
string articles[14] = {"a","A","an","aN","An","AN","the","The","tHe","thE","THe","tHE","ThE","THE"};
ifstream rfile;
rfile.open(file.c_str());
if(rfile.fail()){
cerr << "Error while attempting to open the file." << endl;
return 0;
}
string::size_type pos;
string word;
string words[1024];
while(getline(rfile,line)){
istringstream iss(line);
for(int i = 0; i <= line.length(); i++){
iss >> word;
words[i] = word;
for(int j = 0; j <= 14; j++){
if(word == articles[j]){
string article = word;
iss >> word;
pos = line.find(article);
//cout << pos << endl;
string adjec = capitalization(word,adj);
int position = (pos + word.length());
line.insert(position, " " + adjec);
continue;
}
}
}
cout << line << "\n";
}
}
This may not fix any of your problems, but...
The logic in these lines is wrong.
istringstream iss(line);
for(int i = 0; i <= line.length(); i++){
iss >> word;
Let's say your line is
This is a test.
For this line, line.length() is 15 but there aren't 15 words. What you need is
istringstream iss(line);
while ( iss >> word ) {
For some reason I am getting zero values in my vector when I try to read from a txt file.
Here is my code:
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
while (read >> n){
source.push_back(n);
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}
The txt file is rather long but the format is:
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
Here is reading one by one:
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main(){
ifstream read("e:\\problem13.txt");
vector<int> source;
char n;
while (read >> n){
source.push_back(n - '0');
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << endl << "Size: " << source.size() << endl << "Finished.";
}
But i recommend you reading line by line or if the file is no so big reading all in an std::string and process the string (reading from file is expensive).
In order to store each digit as an int, read each line and store it in a string. Then process each line.
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
string line;
while (read >> line){
string::iterator iter = line.begin();
string::iterator end = line.end();
for ( ; iter != end; ++iter )
{
n = (*iter) - '0';
source.push_back(n);
}
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}
I have a data file comprised of thousands of float values and I want to read them into a 2D vector array and pass that vector to another routine once it's stored the floats from the file. When I run this code it prints out;
[0][0] = 0, [0][1] = 0, etc.
The data file contains values like;
0.000579, 27.560021, etc.
int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");
for(int i = 0; i < rows; i++){
for(int j = 0; j < 2; j++){
in >> dataVec[i][j];
cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
}
}
in.close();
It looks to me like the file could not be opened. You did not test for success, so it will plough on regardless. All your values were initialized to zero and will stay that way because every read fails. This is conjecture, I admit, but I'd put money on it. =)
Try this solution, it works according to your specs:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(void)
{
ifstream infile;
char cNum[10] ;
int rows = 1;
int cols = 2;
vector<vector<float > > dataVec(rows,vector<float>(cols));
infile.open ("test2.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < 2; j++)
{
infile.getline(cNum, 256, ',');
dataVec[i][j]= atof(cNum) ;
cout <<dataVec[i][j]<<" , ";
}
}
}
infile.close();
}
else
{
cout << "Error opening file";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
void write(int m, int n)
{
ofstream ofs("data.txt");
if (!ofs) {
cerr << "write error" << endl;
return;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
ofs << i+j << " ";
}
void read(int m, int n)
{
ifstream ifs("data.txt");
if (!ifs) {
cerr << "read error" << endl;
return;
}
vector<float> v;
float a;
while (ifs >> a) v.push_back(a);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cout << "[" << i << "][" << j << "] = "
<< v[i*n+j] << ", ";
}
int main()
{
write(2,2);
read(2,2);
return 0;
}