Displaying contents of vector - c++

I am having trouble displaying the contents of a vector. I am unsure whether it is the way I read in the values from the text file, or whether my display function is just not working.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string line;
int n,length;
std::vector<int>arr1;
fstream file("t1.txt");
if(file.is_open())
{
while (getline(file,line))
{
cout << line << endl;
}
file << line;
length = line.length();
while(file >> n)
arr1.push_back(n);
for(int i =0; i < (int)arr1.size(); i++)
cout << arr1.at(i) << endl;
}
return 0;
}
Any help would be greatly appreciated.
the text file contains "5 2 5 5 -1 7 2 5 3 5 2 -2"

I suppose you have a problem with vector building (reading values from file to vector). You should delete (or comment) expression with getline, as well as writing line back to file (file << line), and use only file >> n.
Try the following shortened version of your program
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string line;
int n;
std::vector<int> arr1;
fstream file("t1.txt");
if(file.is_open())
{
while(file >> n)
arr1.push_back(n);
for(int i =0; i < (int)arr1.size(); i++)
cout << arr1.at(i) << endl;
file.close();
}
return 0;
}
Problem of your initial code is that after you read line from your file (that comprises only one line) next reading (whether it is file >> ... or getline(...)) will provide no data because END OF FILE. To read data from file again you should re-open it
...
length = line.length();
file.close();
file.open("t1.txt");
while(file >> n)
arr1.push_back(n);
...
or rewind to the beginning
...
length = line.length();
file.clear();
file.seekg(0, ios_base::beg);
while(file >> n)
arr1.push_back(n);
...
But you should understand, that writing to file stream does not provide desired effect - the recorded data will be available only after transfer written data from the buffer to the file (in the general case, after the file closing).
EDIT:
Also I want to add, that C++ allows input to and output from vector without additional loops, just consider the following example
if(file.is_open())
{
// filling vector from the stream
istream_iterator<int> it(file); // iterator for int values in file
istream_iterator<int> eos; // end of straem
arr1.insert(arr1.begin(), it, eos);
// output vector to the stream (cout = standard output stream)
ostream_iterator<int> oit (cout,"\n"); // "\n" = new line is a separator for output
// also " " or any other separator can be used
copy(arr1.begin(), arr1.end(), oit);
}

Related

How to get the lines of a file and the amount of characters per line

I am trying to get the amount of lines in a file in order to make an array to store the characters of each line. I think the problem is with the two while loops iterating at the same time.
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
int main(int argc, char *argv[]){
cout << "input file" << endl;
string file;
cin >> file;
ifstream inFile;
inFile.open(file, ios::in);
cout << "success1";
if (inFile.is_open()) {
vector<double> inputs;
string line;
string s;
int current;
int sTotal;
while(!inFile.eof()) {
getline(inFile, s);
sTotal++;
}
while (!inFile.eof()) {
getline(inFile, line);
cout << "success2";
char *lineArr = new char[line.length()][sTotal];
for(int j = 0;j < sTotal;j++){
for (int i = 0; i < sizeof(lineArr); i++) {
lineArr[i] = line[i];
}
}
}
}else cout << "fail";
}
Any help would be appreciated. Im probably looking at this all wrong.
A main issue with your code is that you consume the stream in the first while loop and then try to do it again. They are not "iterating at the same time", they are two successive loops with the same exit condition. In virtually every case that results in the second one not executing at all.
Also, if you are allowing yourself to use str::string and std::vector, avoid using char*, it only adds confusion.
Try a single loop, using a vector<string> to push each line you get and print in the end the length of the loop. Have a look at these links: std::vector, getline
A rough sketch of what I mean:
vector<string> lines;
string line;
while(getLine(inFile, line)){
lines.push(line);
}
cout << lines.size() << endl;
Then if you want to count the words per line, iterate again through the vector, and split each element; there are several ways to do that as well.

c++ how to read and write from a specific line in a textfile?

hi I am trying to read a specific line from a text file update that and put it back to the same line without affecting the other lines in c++
here I am trying to execute the code and values get added when I re-execute it
#include <iostream>
#include <stream>
#include <stdio.h>
#include <string>
#include <stream>
using namespace std;
void stringGen(char num){
ifstream ifile;
ifile.open("example1.txt");
if(ifile) {
int LINE = 5;
string line;
ifstream myfile1 ("example1.txt");
for (int i = 1; i <= LINE; i++)
getline(myfile1, line);
cout << line<<endl;
stringstream geek(line);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
ofstream MyFile("example1.txt");//
MyFile.close();
}
else{
num=61001;
ofstream MyFile("example1.txt");//
MyFile << num;
MyFile.close();
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("example1.txt");//
MyFile << num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}
At first, you need to understand, how files, with lines are stored. Simplified, it is a sequence of bytes, one byte after the other. There maybe some special characters in this byte sequence, which people can interprete as the end of a line, e.g. '\n'. But also other characters or even more than one character is possible:
If you look at the following text.
Hello1
World1
Hello2
World2
it maybe stored in a file like this:
Hello1\nWorld1\nHello2\nWorld2\n
And just because we interprete a '\n' as the end of the line, we can "see" lines in there.
So, if you want to modify a line, then you would need to find the start position of the thing that we interprete as a line in the file, and then modify some bytes.
That can of course only be done, if the length of the "line" will not change. Then you could use "seek" functions and overwrite the needed bytes.
In reality, nobody would do that. Normally, you would read "lines" of the file into some kind of memory buffer, then do the modification there and then write back all lines.
For example, you would define a std::vector and then read all lines, by using std::getline and push_back the lines in the std::vector.
The modifications will be done in the std::vector, and the all data will be written back to the file, overwriting all "old" data.
There are more answers to this question. If you have any more specific question, I will answer again
Some simple example code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
// Here we will store all lines of the text file
std::vector<std::string> lines{};
// Open the text file for reading and check, if it could be opened
if (std::ifstream textfileStream{ "test.txt" }; textfileStream) {
// Read all lines into our vector
std::string oneLine{};
while (std::getline(textfileStream, oneLine)) {
// Add the just read line to our vector
lines.push_back(oneLine);
}
// For test purposes, modify the first line
if (not lines.empty()) lines[0] = "MODIFIED";
}
else std::cerr << "\nError: Could not open input text file\n";
// Write back data
// Open the text file for writing and check, if it could be opened
if (std::ofstream textfileStream{ "r:\\test.txt" }; textfileStream) {
// Iterate over all lines and wriite to file
for (const std::string& oneLine : lines)
textfileStream << oneLine << '\n';
}
else std::cerr << "\nError: Could not open output text file\n";
return 0;
}
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
void stringGen(char num){
int count=0;
int a;
string line,check,linex;
string msg="Message_Handler:";
fstream ifile;
ifile.open("sample.txt",ios::in|ios::out);
if(ifile){
while(getline (ifile,line)) {
if (line.find("Message_Handler:") == 0){
check=line.substr(16,5);
count++;
a=ifile.tellp();
}
}
ifile.close();
if(count==0){
int num=61001;
cout<<num<<endl;
num=num+1;
ofstream examplefile ("sample.txt",ios::app);
examplefile<<"Message_Handler:"<<num;
examplefile.close();
}
if(count==1){
cout<<check<<endl;
stringstream geek(check);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
else{
int num=61001;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("sample.txt",ios::app);
MyFile <<"Message_Handler:"<< num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}

Read a .dat File and create an array C++

I try to read a .dat file with a list of coordinates X and Y. My code work to count the lines in the file but it doesn't work to read the coordinates correctly. In the output just show me the number of lines in the .dat file, but it doesn't show me the coordinates. .dat file has 2 column and more than 5 rows (I have many files with different amount of coordinates). Any help is super welcome, i am very new in C++.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main() {
std::vector<int> numbers;
ifstream fileB;
const int SIZE=10;
char filas_dat [SIZE];
fileB.open("Verticesfixed_cell1slc44.dat");
std::string line;
int counter=0;
while (getline(fileB, line)) //contador de filas
{
++counter;
}
if(!fileB.good())
{
int current_number = 0;
while (fileB >> current_number){
numbers.push_back(current_number);}
fileB.close();
cout << "The numbers are: ";
for (int count = 0; count < numbers.size(); count++){
cout << numbers[count] << " ";}
cout << endl;
}
else
{
cout << "Error!";
}
return 0
}
The problem is that after you've counted the number of lines you are at the end of the file, so there is nothing more to read. A file doesn't reposition itself back to the beginning automatically. You have to tell the file to go back to the beginning.
A second similar problem is that when you get to the end of your file the getline function fails (because there's nothing more to read). That puts your file into an error state when nothing will work until you clear the error state.
Finally the call to !fileB.good() is unecessary. The file will never be good at this point, again this is because getline has failed.
Try this code
while (getline(fileB, line)) //contador de filas
{
++counter;
}
fileB.clear(); // clear the error state
fileB.seekg(0); // go back to the beginning of the file
int current_number = 0;
while (fileB >> current_number)
{
numbers.push_back(current_number);
}

C++ while, for and array

Hey guys I stuck working on an assignment in which I asked to write a program that lists the contents of a file.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string array[5];
ifstream infile("file_names.txt");
int x=0;
while(infile>>array[x++]){
for(int i=0;i<=x;i++){
infile >> array[i];
cout << array[i] << endl;}}
}
basically I have a file named "file_names.txt" that contains three strings and I want my program to list them.
you don't need two loops.
int main() {
int array_size=5;
string array[array_size];
ifstream infile("file_names.txt");
int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
cout << array[i] << endl;
i++;
}
}
Your assignment was
an assignment in which I asked to write a program that lists the contents of a file.
One way of printing the contents of a file could be
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("my_file.txt", ios::in); // open input stream
if(!fin){ // check state, that file could be successfully opened
printf("Error opening file.");
return 1;
}
while(fin.peek() != EOF){
cout << (char)fin.get();
}
fin.close(); // close input stream
return 0;
}
This code demonstrates some basic C++ functionality like
opening an input stream, checking the state of the input stream and reading the contents character by character. Try to understand each step.
I know I can get to the same result like this
string array[50];
ifstream infile("file_names.txt");
for(int i=0; **i<3**; i++){
infile >> array[i];
cout << array[i] <<endl;}
But the whole point is to use a while loop because there might be more or less than 3 items

Read a file of strings with quotes and commas into string array

Let's say I have a file of names such as:
"erica","bosley","bob","david","janice"
That is, quotes around each name, each name separated by a comma with no space in between.
I want to read these into an array of strings, but can't seem to find the ignore/get/getline/whatever combo to work. I imagine this is a common problem but I'm trying to get better at file I/O and don't know much yet. Here's a basic version that just reads in the entire file as one string (NOT what I want, obviously):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
fstream iFile("names.txt", ios::in);
string names[5];
int index = 0;
while(iFile)
{
iFile >> names[index];
index++;
}
for(int i = 0; i < 5; i++)
{
cout << "names[" << i << "]: " << names[i] << endl;
}
Output:
names[0]: "erica","bosley","bob","david","janice"
names[1]:
names[2]:
names[3]:
names[4]:
Also, I understand why it all gets read as a single string, but then why are the remaining elements not filled with garbage?
To be clear, I want the output to look like:
names[0]: erica
names[1]: bosley
names[2]: bob
names[3]: david
names[4]: janice
The easiest way to handle this:
Read the entire file and place it into a string, Here is an example of how to do it.
Split the string that you got from number 1. Here is an example of how to do that.
Stream extraction delimits by a space. Therefore the entire file gets read as one string. What you want instead is to split the string by commas.
#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
fstream iFile("names.txt", ios::in);
string file;
iFile >> file;
std::istringstream ss(file);
std::string token;
std::vector<std::string> names;
while(std::getline(ss, token, ',')) {
names.push_back(token);
}
To remove the quotes, use this code:
for (unsigned int i = 0; i < names.size(); i++) {
auto it = std::remove_if(names[i].begin(), names[i].end(), [&] (char c) { return c == '"'; });
names[i] = std::string(names[i].begin(), it);
}
remove_if returns the end iterator for the transformed string, which is why you construct the new string with (s.begin(), it).
Then output it:
for (unsigned int i = 0; i < names.size(); i++) {
std::cout << "names["<<i<<"]: " << names[i] << std::endl;
}
Live Example