C++ while, for and array - c++

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

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.

stock data from file into arrays c++

I have this specific code to read integers from a text file:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
bool contains_number(const string &c);
int main()
{
int from[50], to[50];
int count = 0;
{
string line1[50];
ifstream myfile("test.txt");
int a = 0;
if (!myfile)
{
cout << "Error opening output file" << endl;
}
while (!myfile.eof())
{
getline(myfile, line1[a]);
if (contains_number(line1[a]))
{
count += 1;
myfile >> from[a];
myfile >> to[a];
//cout << "from:" << from[a] << "\n";
//cout << "to:" << to[a] << "\n";
}
}
}
return 0;
}
bool contains_number(const string &c)
{
return (c.find_first_of("1:50") != string::npos);
}
I need to stock these values of from[] and to[] in 2 arrays to use them n another function, I tried to create 2 arrays in a simple way and affect the values for example:
int x[], y[];
myfile >> from[a];
for(int i=0; i<50;i++)
{
x[i] = from[i];
}
but it doesn't work. It seems that this way is only to read and display and a value in from will be deleted once another value comes.
Any help?
Thanks.
You're not incrementing your array index a in your loop. This results in line[0], to[0] and from[0] to be overwritten for every line in the file where contains_number returns true.
There is no reason for you to save your lines into memory. You can just process your lines as you go through the file (i.e. create a string line variable in your while loop).
Make sure you properly close your file handle.
Aside from that you should check your index bounds in the loop (a < 50), else you might be writing out of bounds of your arrays if your file has more numbers than 50.
A better solution yet would be to use vectors instead of arrays, especially if your file may contain any number of numbers.

Displaying contents of vector

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);
}

segmentation fault (core dumped) reading line into array

I'm trying to read in a file into an array so that I could process the array into selection sort. But when I try to read in the file, I get a segmentation fault(core dumped) error. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string array[40707];
int loop = 0;
int loop2;
string line;
ifstream inFile("beowulf.txt");
if (inFile.is_open())
{
while(!inFile.eof())
{
getline(inFile, line);
array[loop] = line;
loop++;
}
inFile.close();
}
else cout << "Unable to open file" << endl;
for (loop2 =0; loop2 <= loop; loop2++)
cout << array[loop2] << endl;
return 0;
}
Change your string array to:
std::vector<std::string> array;
Then you can read the file and copy into the vector simply as:
std::copy(std::istream_iterator<std::string>(inFile),
std::istream_iterator<std::string>(),
std::back_inserter(array));
EDIT: To read the file line-by-line, either define your own insert_iterator or do it like this:
std::string line;
while (getline(inFile, line))
array.push_back(line);
Your code will then change to something like this
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> array;
string line;
ifstream inFile("beowulf.txt");
if (!inFile.is_open()) {
cerr << "Unable to open file" << endl;
return 1;
}
while (getline(inFile, line))
array.push_back(line);
inFile.close();
for (int i = 0; i < array.size(); ++i)
cout << array[i] << endl;
return 0;
}
Two potential error cases I can see right away.
Overrunning the end of the end of array. It can happen while reading because there is no guard on loop. If the array read was exactly 40707 lines it will happen while printing out when loop2 == loop. Either of these is probably the cause of the segfault. The recommended solution is to use C++'s std::vector because it will dynamically size itself to the input and automate iterating through the items stored.
The second error is less severe, but allows an infinite loop on an IO error. The end of file may never be reached if an error prevents reading a line and places the stream in an error condition. Unlikely to happen with getline, but a common occurrence with formatted reads.
Using most of the OP's solution:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> array; // vector eliminates buffer overflow problem of string array.
//int loop = 0; vector also eliminates the need for this counter
//int loop2; and this one
string line;
ifstream inFile("beowulf.txt");
if (inFile.is_open())
{
while(getline(inFile, line)) //exits if anything goes wrong with the file IO
{
array.push_back(line); // stores line in vector
}
inFile.close();
}
else cout << "Unable to open file" << endl;
// C++11 way
for (string const & str: array)
{ // iterates through the string automatically
cout << str << endl;
}
/* Old C++ way
for (vector<string>::iterator str = array.begin();
token != array.end();
++token)
{ // iterates through the string manually
cout << *str << endl;
}
*/
return 0;
}

Reading in a text file from a command line and storing the content of the file into a c-string

I am learning C++ in one of my classes and I am having difficulties storing the content of a .txt file into a c string.
I have figured out how to validate that the .txt file exists but when I try storing the characters into a c-string it crashes.
This is my most recent attempt:
char * fileContent[MAX_SIZE];
ifstream ifile(argv[1]);
while (int i = 0 < MAX_SIZE)
{
ifile >> fileContent[i];
cout << fileContent[i];
if (ifile.eof())
break;
i++;
}
ifile.close();
Every-time the console gets to the loop it crashes. Are there any suggestions to help make this work?
I need it to be a c-string so that I can run the c-string through other functions. I am still pretty new to C++.
The assignment states: "Reads a text file into memory, one byte at a time"
I hope what I am trying to do is this.
Thank you
You can use the following code to read from a text file and save the string as a C-string. The output file (output.txt) contains the c-string output.
#include <string>
#include <iostream>
#include <fstream>
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
char *out_c_string;
char ch;
int index=0;
while(cin >> ch)
out_c_string[index++] = ch;
for(int i=0; i<index; i++)
cout << out_c_string[i]; // the c string of the file :)
return 0;
}
There were few bugs in your code, try this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int MAX_SIZE = 128;
int main(int argc, char* argv[])
{
char fileContent[MAX_SIZE]; //bad idea never do that!
// use an std::vector<char> instead!
// and reverse a minimum amount of chars
// using `reserve` if you are after performance
ifstream ifile(argv[1]);
int i = 0;
while (i < MAX_SIZE)
{
ifile >> fileContent[i];
cout << fileContent[i];
if (ifile.eof())
break;
i++;
}
ifile.close();
}
Combining everyones answers, I got this as my function:
void get_file_info(char * argv, char (&fileContent) [MAX_SIZE], int & filesize ){
freopen(argv, "r", stdin);
char ch;
int index = 0;
while (cin >> noskipws >> ch)
fileContent[index++] = ch;
cout << endl << index << endl;
#if SHOW_DEBUG_CODE
for (int count = 0; count < index; count++)
cout << fileContent[count];
#endif
fclose(stdin);
}
It seems to work just fine. I will look into vectors my next free time but for right now, I am going to continue with char array.
Thank you for your suggestions.
I would do this. It's more general to cope with any size file.
void ReadFile(char*file,char**buff,int*size){
// Open file as binary putting file position at the end
ifstream is(file,ios::binary|ios::ate);
// Get the current file position, which is the file end
*size=is.tellg();
// Put file pointer back at the start
is.seekg(0,ios::beg);
// errors
if (!*size){
cout<<"Unable to open input file or file empty\n";
exit(9);
}
// allocate a buffer one bigger to allow for zero terminator
*buff=new char[*size+1];
// read the whole file in one hit
is.read(*buff,*size);
// Done. So close and zero delimit data.
is.close();
*(*buff+*size)=0;
}