I am trying to read some integer numbers from a text file in C++. It is weird problem that it reads only 13 numbers , but my file contains 25 numbers . I searched but not found any thing , someone suggested to add ios::binary , but not working.
Why ??
here is this part of code.
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("Nvector.txt");
vector<int> N;
for(int j=0; j<25; j++)
{
int input;
myfile>> input;
N.push_back (input);
}
system("PAUSE");
return 0;
}
You might want to check the text file that you're reading from, there can be special end of line characters that will cause the integers to be concatenated/removed from the vector, there might also be problems related to the vector
Related
I am reading a CSV file into vector of string vectors. I have written code below.
#include<iostream>
#include<fstream>
#include<string>
#include <vector>
#include <fstream>
#include <cmath>
#include <sstream>
using namespace std;
int main()
{
ifstream mesh;
mesh.open("mesh_reference.csv");
vector<vector<string> > point_coordinates;
string line, word;
while (getline(mesh,line))
{
stringstream ss(line);
vector<string> row;
while (getline(ss, word, ','))
{
row.push_back(word);
}
point_coordinates.push_back(row);
}
for(int i=0; i<point_coordinates.size(); i++)
{
for(int j=0; j<3; j++)
cout<<point_coordinates[i][j]<<" ";
cout<<endl;
}
return 0;
}
When I print out the vector of vectors, I see that I am loosing the first character of Element at 0 position in the vector row. Basically, point_coordinates[0][0] is displaying 0.0001 while the string is supposed to be -0.0001. I am not able to understand the reason for the same. Kindly help.
A typical output line is
.0131 -0.019430324 0.051801
Whereas the CSV data is
0.0131,-0.019430324,0.051801
SAMPLE CSV DATA FROM FILE
NODES__X,NODES__Y,NODES__Z
0.0131,-0.019430324,0.051801
0.0131,-0.019430324,0.06699588
0.0131,-0.018630324,0.06699588
0.0131,-0.018630324,0.051801
0.0131,-0.017630324,0.050801
0.0131,-0.017630324,0.050001
0.0149,-0.017630324,0.050001
0.0149,-0.019430324,0.051801
Although the problem is already solved, I would like to show you a solution using some modern C++ algorithms and eliminating minor issues.
Do not use using namespace std;. You should not do this
Ne need for a separate file.open. The std::ifstream constructor will open the file for you. And the destructor will close it
Check if the file could be opened. The ifstreams ! operator is overloaded. So you can do a boolean check
Do not use int in for loops where you compare against .size(). Use ````size_t instead
Always initialize all variables, even if there is an assignement in the next line
For tokenizing you should use std::sregex_token_iterator. It has exactly been designed for this purpose
In modern C++ you are encouraged to use algorithms
Please see an improved version of your code below:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <regex>
const std::regex comma(",");
int main()
{
// Open source file.
std::ifstream mesh("r:\\mesh_reference.csv");
// Here we will store the result
std::vector<std::vector<std::string>> point_coordinates;
// We want to read all lines of the file
std::string line{};
while (mesh && getline(mesh, line)) {
// Tokenize the line and store result in vector. Use range constructor of std::vector
std::vector<std::string> row{ std::sregex_token_iterator(line.begin(),line.end(),comma,-1), std::sregex_token_iterator() };
point_coordinates.push_back(row);
}
// Print result. Go through all lines and then copy line elements to std::cout
std::for_each(point_coordinates.begin(), point_coordinates.end(), [](std::vector<std::string> & vs) {
std::copy(vs.begin(), vs.end(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << "\n"; });
return 0;
}
Please consider, if you may want to use such an approach in the future
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need help storing text from a text file into a vector.
The text file is called "names.txt" and it has the following data
salman
mahmoud
ahmad
ghadeer
raghad
abdullah
faisal
The text below is my code
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
vector<string> STRING;
ifstream infile;
infile.open ("names.txt");
for(size_t i = 0; i < 7; i++)
{
getline (infile, STRING[i]);
cout << STRING[i];
}
infile.close();
return 0;
}
Everytime I run the program, I get the following error message
You declared your vector, but you did not set its size.
You can:
Either declare a vector with a specific size
or simply use push_back() function like below:
.
for(size_t i = 0; i < 7; i++)
{
string temp; // temporal variable - just a place holder
getline (infile, temp); // get line
MyVector.push_back(temp); // add it to the vector (add to the end of it)
}
You are trying to access elements of the vector which are not created.
When you call
vector<string> STRING
it creates a vector capable of storing strings, but not having any.
So, when you a trying to access one of them with STRING[i], it says that you are trying to access non-existing element.
Possible solution: before the loop call
STRING.resize(7);
It'll allocate memory for 7 empty strings and then this loop will work just fine.
You can try this way :
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
vector<string> STR;
ifstream infile;
infile.open ("names.txt");
for(size_t i = 0; i < 7; i++)
{
string st;
getline (infile, st);
STR.push_back(st);
cout << STR[i] << endl;
}
infile.close();
return 0;
}
Your problem is that you are trying to write to an empty vector. This can easily be fixed by simply change:
vector<string> STRING;
to:
vector<string> STRING(7);
However, you should change the name of the vector to something like:
vector<string> lines;
One last thing (less important) is the fact that you read 7 lines from the file. What if the file has 4 lines or maybe 56 lines? So, here's what you should really do:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main () {
std::vector<std::string> lines;
std::ifstream infile("names.txt");
std::string line;
while(std::getline(infile, line)) {
lines.push_back(line);
std::cout << lines.back() << std::endl;
}
return 0;
}
I wrote this in an attempt to copy the contents of one text file into another based on command-line arguments:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
if(argc != 3) {
cout << "invalid args!";
return 0;
}
fstream op(argv[1], ios::in);
vector<string> list;
string line;
while(!op.end)
op >> line;
list.push_back(line);
op.close();
op.open(argv[2], ios::out);
for(unsigned int i = 0; i < list.size(); i++)
op << list[i];
op.close();
return 0;
}
It does not produce any syntax errors, but a logic error is evident: there is no output.
So apart from the lack of error-checking and the fact that there are more efficient ways to do this, what is wrong with my code? That is, why will it not copy file with name argv[1] to a file named argv[2]?
You have a bug: your while loop's body is not enclosed in {}, so only op >> line is executed until the file is read completely, and the last value of line is then pushed onto the vector.
EDIT: By the way, that's a very good illustration for why you should let your editor do your code indentation; the way your while loop looked, it was hard to spot this mistake.
There are several issues in your code:
With streams you shall not loop on end or eof (have a look at the many SO questions/answers about this).
The enclosing {} issue that Marcus revealed
You are not reading lines but words (operator>> uses spaces as separators) and squizing the whitespaces in the output.
Here how to tackle all this:
while(getline(op, line))
list.push_back(line);
and of course for the output: op << list[i]<<endl;
For one-to-one copy, you may also consider the following code - handles binary data, uses less memory and is shorter:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
using namespace std;
int main(int argc, char *argv[])
{
if (argc < 3)
return 1;
fstream s(argv[1], ios::in);
fstream d(argv[2], ios::out);
copy(
istreambuf_iterator<char>(s)
, istreambuf_iterator<char>()
, ostreambuf_iterator<char>(d));
return 0;
}
So this is a fairly simple example of a program where I'm trying to output the first two lines of an input text file. The ifstream should be a global variable, and the testGetFile() function is necessary (I have not done the actual text processing needed in this code.) I'm trying to figure out why this is cout-ing only the SECOND line of the input file. Any help will be appreciated!
Thanks in advance!
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
ifstream input;
string testGetFile(){
string result;
getline(input,result);
return result;
}
int main(){
input.open("testInput.txt");
cout<< testGetFile();
cout<< testGetFile();
return 0;
}
I am trying to write a program which will declare an array of 5 structs from information read from a file. Then I use a loop to the print the information of every element in the array.
The code I have written only seems to read one line from the txt. file. Any tips or advice would be appreciated.
#include <istream>
#include <iostream>
#include <ostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main ()
{
struct Bankinfo{
string name;
int accountnum;
float checking;
float savings;
string phone;
} bankinfo[5];
int i;
i=0;
cout<<"This is a test program"<<endl;
char x;
x=0;
for (i=0;i<=6;i++)
{
ifstream infile;
char testinfo [10001];
infile.open("testinfo.txt");
cin.get(testinfo,10001);
cout<<testinfo<<endl;
infile>>bankinfo [i].name>>bankinfo [i].accountnum>>bankinfo [i].checking>>bankinfo [i].savings>>bankinfo [i].phone;
cout<<setw(10) << (bankinfo[i].name);
cout<<setw(10) <<(bankinfo [i].accountnum);
cout<<setw(10) <<(bankinfo [i].checking);
cout<<setw(10) <<setprecision (2)<<fixed<<(bankinfo [i].savings);
cout<<setw(15) <<(bankinfo [i].phone);
}
cout<<" "<<endl;
cout<<"Thanks for using the program"<<endl;
return (0);
}
You're opening the file in each iteration of the loop in i. Try to get out of the loop the infile.open(...). Now it will read more lines. I don't see the purpose of that cin.get(...) either.