I am currently working in c++. My goal is to be able to implement the A* algorithm, through a series of steps I plan to be able to store, and list the shortest path from Point A to Point B.
My program will take in a command-line argument which will be a file to read in. The purpose of giving the program a file t read in is that each file is its own "grid" for A* to process. The format for the grid file is as follows:
Num 1 = WIDTH and then Num 2 = HEIGHT
o = start
* = finish
. = passable node
# = impassable wall
So an example grid, let's call it "Grid1", would be:
8 5
o......#
......##
.....###
....####
.......*
So to process this, when you run the program you would pass in "Grid1".
From here, I plan to create a filestream and read in each character into a 2D Array/Vector to attempt to recreate the grid so I can have positions. For example, in "Grid1" the character "o" would be at position [0][0] in a Array/Vector. My attempted implementation is as follows:
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>
using namespace std;
int main(int argc, char *argv[])
{
//Checking for CLA
if( argc < 1 )
{
cout << "Program must take atleast <1> arguments!" << endl << "1) File to read 2) OPTIONAL: Type of search" << endl;
}
//CLA #1 is the file containing GRID to be read in
string gridTBO = argv[1];
//Start new filestream and open grid file for reading
ofstream gridFile;
gridFile.open( gridTBO );
//Check to make sure we can even open the file before proceeding
if( gridFile.is_open() )
{
//To store grid data
vector<string> grid;
grid[0][0].push_back("Hello");
cout << grid[0][0];
}
However, in regards to my "push_back", it seems that I am not able to print out or throw the data into the vector. I would primarily want each index such as [0][0] [0][1] [0][2] to hold each individual character in order to recreate a grid like the one I pass in.
I am not quite sure what I am doing incorrectly as I am fairly inexperienced using vectors, however, the code for pushing data into the grid is purely for testing purposes. Once I am able to parse some data into the vector, I would then like to automate it with a loop and have "getline" or a similar function grab the data for me.
So my main questions are:
1) Why is my push_back and print out failing?
2) How would I read in char by char with a loop to prevent me from manually putting data in?
The error I receive on run-time is:
Segmentation Fault(core dump)
Thank you everyone in advance for your assistance and knowledge!
ofstream is for output file. Use ifstream for reading the file.
vector<string> grid;
vector<string> will work in your case. But it's easier to create a 2-D array of vector with vector<vector<char>>, then you access grid[x][y]
Unlike arrays, vectors don't have any elements when they are created, so there is no valid grid[x][y] or grid[x] until you add something to it.
Try this code instead:
int main()
{
ifstream fin("test.txt");
vector<vector<char>> grid;
int row = 0;
string line;
while(fin >> line)
{
grid.resize(row + 1);
for(auto c : line)
grid[row].push_back(c);
row++;
}
for(auto row_vector : grid)
{
for(auto e : row_vector)
cout << e;
cout << "\n";
}
return 0;
}
Related
I have text file that is a large list of integers separated by commas.
E.g. "1,2,2,3,3,4,1,3,4,10".
Every two integers represents a vertex adjacency in a graph.
I want to create some C++ code that reads the text file and recognizes every two integers as some sort of data structure (such as a Boolean for yes/no adjacent).
Additionally I will be creating a class that colors this graph using these adjacencies. Being able to have the code remember what color or value each vertex has been given (this is not as important yet as just getting the program to parse in the data from the text file), but help with this would be appreciated or appear in a later question.
How would I do this in C++?
Assuming that the input file is one line comprised of a list of integers with a comma as the separator.
Seems like the mains steps are to:
Read in the the line as a string.
Parse the individual numbers out of the string (using ',' as the delimiter). So that each number is its own separate string.
Convert those individual strings to integers.
Once you have a vector of integers it should be pretty straightforward to get every pair and do as you wish.
Example:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main() {
fstream inFile;
inFile.open("input.txt"); // File with your numbers as input.
string tempString = "";
getline(inFile, tempString); // Read in the line from the file.
// If more than one line per file you can put this whole thing in a loop.
stringstream ss(tempString); // Convert from a string to a string stream.
vector<string> numbers_str = vector<string> (); // string vector to store the numbers as strings
vector<int> numbers = vector<int> (); // int vector to store the numbers once converted to int
while(ss.good()) // While you haven't reached the end.
{
getline(ss, tempString, ','); // Get the first number (as a string) with ',' as the delimiter.
numbers_str.push_back(tempString); // Add the number to the vector.
}
// Iterate through the vector of the string version of the numbers.
// Use stoi() to convert them from string to integers and add then to integer vector.
for(int i=0; i < numbers_str.size(); i++)
{
int tempInt = stoi(numbers_str[i], nullptr, 10); // Convert from string to base 10. C++11 feature: http://www.cplusplus.com/reference/string/stoi/
numbers.push_back(tempInt); // Add to the integer vector.
}
// Print out the numbers ... just to test and make sure that everything looks alright.
for(int i = 0; i < numbers.size(); i++)
{
cout << i+1 << ": " << numbers[i] << endl;
}
/*
Should be pretty straight forward from here.
You can go iterate through the vector and get every pair of integers and set those as the X and Y coor for your
custom data structure.
*/
inFile.close(); // Clean up. Close file.
cout << "The End" << endl;
return 0;
}
If your file has more than one line then you can just extend this and do the same thing for every line in your file.
Hope that helps.
I am currently trying to do an assignment in my C++ class. I think I've gotten as far as I can on my own.
The assignment calls for me to read names from a text file, put the names in order, and write them to a new file.
The names in the given text file are formatted as follows:
Jackie Sam Tom Bill Mary Paul Zev Barb John
My code that I have for the assignment:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string nameArray[26] = {};
int main() {
// Defined variables
int y = 65, lineNumber = 0;
string readName;
// Opens the text file LineUp
ifstream readfile;
readfile.open("LineUp.txt");
// Opens the text file InOrder
ofstream outfile;
outfile.open("InOrder.txt");
// Read name from file
while (readfile >> readName) {
// If first character of name != char(y),
// run loop
while (readName[0] != char(y)) {
y++;
lineNumber++;
// If first character of name = char(y),
// add name to lineNumber's position in array
if (readName[0] == char(y)) {
nameArray[lineNumber] = readName;
}
}
// Reset values of lineNumber and y
y = 65;
lineNumber = 0;
}
// Writes names in array to file
for (int x = 0; x <= 25; x++)
outfile << nameArray[x] << endl;
// Close files
readfile.close();
outfile.close();
// Print statement so you can see at least
// something happens
cout << "KIDS ORGANIZED. BEEP. BOOP. BEEP.\n";
cin.get();
return 0;
}
The output to the file made in the program that holds the ordered names:
Barb
John
Mary
Paul
Sam
Tom
Zev
(It contains many more empty lines than what stack overflow shows.)
The questions I have are as follows:
1: How can I get rid of the empty spaces in the array for when I want to write the names to the text file InOrder.txt?
2: The names Jackie and Bill are not being shows because the positions in the array are being overwritten by the other two names. How can I check if those positions are filled to add in these two names?
3: Is there anything in my program I can do to make it more efficient or more readable? Or just do better in general, I guess.
A big thank you to anyone willing to try to figure out how to solve these problems!
One problem is the length of your string array. You only reserve 26 elements. In your for loop
for (int x = 0; x <= 26; x++)
outfile << nameArray[x] << endl;
you try to access element 0 to 26 (that are 27 elements in total), that's more than you allocated. You have to change this loop to something like
for (int x = 0; x < 26; x++)
outfile << nameArray[x] << endl;
so it won't crash.
But the main problem in your program is the sorting system. As you already have noticed, as soon as two kids have a name with the same first letter, one name will be overwritten.
A better approach would be to use some of the standard libraries.
First i would not use a std::string array, but a std::vector. A vector is, simply said, a better and dynamic array with a lot more functions. If you want to know more about vectors, check here.
With a vector you can read every name first and sort it later:
std::vector<std::string> nameVector;
while(readfile >> readName) {
//add name to the end of the vector
nameVector.push_back(readName);
}
Now you can use std::sort() to sort the vector.
std::sort(nameVector.begin(), nameVector.end());
And last write everything to your output file:
for(int x = 0; x < nameVector.size(); ++x)
outfile << nameVector[x] << std::endl;
Firstly don't use the nameArray[26] in the for-loop as it is out of range.
Secondly by now surely you must have realized the issue. You logic reserve a place for name with each alhpabet and if there are two names starting with same alphabet it creates problem. Also the blank spaces are ther because of the places in the array not having any names starting with respective alphabet. for example. no name starts with A so a blank space will be in start of the file similary no name starts with C so a blank space would be there after the name Barb.
As per your logic the solution should be something like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Can be many names
string nameArray[100] = {};
int main() {
// Defined variables
int y = 65, lineNumber = 0;
string readName;
// Opens the text file LineUp
ifstream readfile;
readfile.open("LineUp.txt");
// Opens the text file InOrder
ofstream outfile;
outfile.open("InOrder.txt");
//Run while the names are not checked for all alphabets
while (y <= 90) {
// Read names from file till the end is reached
while (readfile >> readName) {
// If first character of name != char(y),
// run loop
if(readName[0] == char(y)) {
// If first character of name = char(y),
// add name to lineNumber's position in array
nameArray[lineNumber] = readName;
lineNumber++;
}
}
}
//Check File for next character
y++;
}
// Writes names in array to file
for (int x = 0; x < lineNumber; x++)
outfile << nameArray[x] << endl;
// Close files
readfile.close();
outfile.close();
// Print statement so you can see at least
// something happens
cout << "KIDS ORGANIZED. BEEP. BOOP. BEEP.\n";
cin.get();
return 0;
}
Note that this code works for only Upper-case letters and sorts only based on first alphabet.
I am writing a program that extracts data from a text file and encrypts it. I am having some trouble with this. First of all there is an error at the getline(data,s[i]) part. Also the text file has two sentences but it only encrypts the second sentence. The other issue with that is It encrypts one letter at a time and outputs the sentence every time. It should output just the sentence encrypted.
#include <iostream>
#include <fstream>
#include <istream>
using namespace std;
int main(){
//Declare Variables
string s;
ifstream data;
//Uses Fstream to open text file
data.open ("/Users/MacBookPro/Desktop/data.txt");
// Use while loop to extract the data from the text file
while(!data.eof()){
getline(data,s);
cout<< s << endl;
}
//Puts the data from the text file into a string array
for(int i = 0; data.good(); i++){
getline(data, s[i]);
cout<< s <<endl;
}
// encrypts the string
if(data.is_open()){
for(int i = 0; i < s.length();i++){
s[i] += 2;
cout << s << endl;
}
}
return 0;
}
In the code below you already reach the end of the stream, and store the last line on the string s.
while(!data.eof()){
getline(data,s);
cout<< s << endl;
}
My suggestion is that you use a list of strings.
vector< string > s;
string tmp;
while(!data.eof()){
getline(data,tmp);
s.push_back(tmp);
cout<< s << endl;
}
The next step you loop through the list and do the encryption
for(i=0; i < s.size(); i++)
{
// encrypt s[i]
}
Hope this helped!
First I had to add this line to get "getline" to be recognised:
#include <string>
Then, there was indeed an error with the line:
getline(data, s[i]);
This is a compilation error, that function is expecting a stream and a string, but you pass it a stream and a char.
Changing that line for:
getline(data, s);
makes your program compile.
However it probably does not do what you want at this point, since the variable i from the for is being ignored.
I suggest that you check out some documentation on the getline function, then rethink what you want to do and try again.
You can fine some doc here:
https://msdn.microsoft.com/en-us/library/vstudio/2whx1zkx(v=vs.100).aspx
Your other concern was that it output your string many times. This is normal, since your cout statement is inside in your encryption loop.
Move it outside the loop instead, to output it only one time once the encryption loop is done.
It is important to spend the time to understand what each line of your program is doing, and why you need it to achieve your goal.
Also when doing something that we find complicated, its easier to do one small part of it at a time, make sure it works, then continue with the next part.
Good Luck :)
Create a temporary string for containing each line and an integer since we're going to find the total number of lines to create an array for all of them.
string temp = "";
int numberOfLines = 0;
Now we try to find the total number of lines
while(data.good()) {
getline(data, temp);
cout << temp << endl;
numberOfLines++;
}
Now we can create an array for all of the lines. This is a dynamic array which you can read on it for more information.
string * lines = new string[numberOfLines];
Now is the time to roll back and read encrypt all the lines. But first we have to go back to first position of file. That's why we use seekg
data.seekg(data.beg);
For each line we read, we'll put in the array and loop through each character, encrypt it and then show the whole sentence.
int i = 0;
while (data.good()) {
getline(data, lines[i]);
i++;
for (int j = 0; lines[i].size(); j++ ) {
lines[i].at(j) += 2;
}
cout << lines[i] << endl;
}
Voila!
s[i] is a character in the string (actually, a character reference), not the string object itself. string::operator[] returns a char& in the docs. See here.
Consider declaring a std::vector<string> string_array; and then use the string_array.push_back(data) member function to append strings from the file onto the vector. Use a for loop to iterate through the vector at a later time with a vector<string>::iterator or the std::vector::size function to get the length of the vector for a traditional for loop (via a call to string_array.size()). Use the square brackets to get each string from the vector (string_array[0 or 1 or etc.]).
Get characters from each string in the vector by using something like string_array[n][m] for the mth character of the nth string. Iterating over each character should be as simple as using the string::length member function to get the string length, and then another for loop.
Also, std::cout << s << std::endl is being used in the wrong places. To output each character, try std::cout << s[i] << std::endl instead, or printf("%c", s[i]), whichever you like.
I'd suggest not using an array to hold strings from the file because you don't know what the array's length will be at runtime (the file size could be unbounded), so a vector is better suited for this case.
Finally, if you need code, there's a beginner's forum post here that I think will help you out. It has a lot of code like yours, but you'll have to modify it for your purposes.
Finally, please use:
std::someCPPLibraryFunction(args);
instead of...
using namespace std;
someCPPLibraryFunction(args);
I've been trying to retrieve saved data from a text file. The data stored are both numbers, separated by a ~. I've managed to get it to print out one of the lines (the top line) however I've been unable to figure out how to proceed through the entire file.
There are only two numbers (integers) on each line, an X and Y position of another vector. The idea is to assign each integer to the respective variable in the vectors. I've not managed to get that far since I can't get it to go past line 1. But I'd thought that by having an array size of 2, and the array temporarily stores the value, assigns it to the vector, then overwrites it with the next value(s) that could work. But again not managed to get that far.
Below is the code I've been trying to use;
........
string loadZombieData;
loadFile >> loadZombieData; //Data gets read from the file and placed in the string
vector<string> result; //Stores result of each split value as a string
stringstream data(loadZombieData);
string line;
while(getline(data,line,'~'))
{
result.push_back(line);
}
for(int i = 0; i < result.size(); i++){
cout << result[i] << " ";
}
.......
Just to clarify, this is not my code, this is some code I found on Stackoverflow, so I'm not entirely certain how it all works yet. As I said, I've been trying to get it to read multiple lines, then using the for loop was going to assign the results to the other vector variables as needed. Any help is appreciated :)
Use two while loops:
std::vector<std::string> result;
std::vector<int> numbers;
std::string filename;
std::ifstream ifile(filename.c_str());
if (!ifile.is_open()) {
std::cerr << "Input file not opened! Something went wrong!" << std::endl;
exit(0);
}
std::string temp;
//loop over the file using newlines as your delimiter
while (std::getline(ifile, temp, '\n')) {
//now temp has the information of each line.
//create a stringstream initialized with this information:
std::istringstream iss(temp);//this contains the information of ONE line
//now loop over the string stream object as you would have in your code sample:
while(getline(iss, temp,'~'))
{
//at this point temp is the value of a token, but it is a string
result.push_back(temp); //note: this only stores the TOKENS as strings
//so to store the token as a int or float, you need to convert it to that
//via another stringstream:
std::istringstream ss(temp);
//if your number type is float, change it here as well as in the vector
//initialization of `numbers`:
int num = 0;
//this checks the stream to ensure that conversion occurred.
//if it did, store the number, otherwise, handle the error (quit - but, this is up to you)
//if stringstreams aren't your cup of tea, try some others (refer to this link):
//http://stackoverflow.com/questions/21807658/check-if-the-input-is-a-number-or-string-c/21807705#21807705
if (!(ss >> num).fail()) {
numbers.push_back(num);
}
else {
std::cerr << "There was a problem converting the string to an integer!" << std::endl;
}
}
}
Note: this version stores the numbers verbatim: i.e. without a sense of how many numbers were on a line. However, that is reconcilable as all you have to do is output n numbers per line. In your case, you know every 2 numbers will be represent the numbers in a line.
This requires:
#include <string>
#include <vector>
#include <cstdlib>
#include <sstream>
I have a large file (50x11k) of a grid of numbers. All i am trying to do is place the values into a vector so that i can access the values of different lines at the same time. I get a seg fault everytime (i cannot even do a cout before a the while loop). Anyone see the issue?
If there is an easier way to do this then please let me know. Its a large file and I need to be able to compare the values of one row with another so a simple getline does not work, Is there a way to jump around a file and not "grab" the lines, but just "examine" the lines so that I can later go back an examine that same line by putting in that number? Like looking at the file like a big array? I wanna look at the third line and 5 character in that line at the same time i look at the 56th line and 9th character, something like that.
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
//int g_Max = 0;
int main() {
vector<vector<string> > grid;
ifstream in("grid.txt");
int row = 0;
int column = 0;
string c;
if (!in) {
cout << "NO!";
}
while (!in.eof()) {
c = in.get();
if ( c.compare("\n") == 0) {
row++;
column = 0;
}
else {
c = grid[column][row];
cout << grid[column][row];
column++;
}
}
return 0;
}
vector<vector<string> > grid;
This declares an empty vector, with no elements.
c = grid[column][row];
This accesses elements of the vector, but there are no elements.
If you change it to use vector::at() instead of vector::operator[] like so:
c = grid.at(column).at(row);
then you'll get exceptions telling you you're accessing out of range.
You need to populate the vector with elements before you can access them. One way is to declare it with the right number of elements up front:
vector<vector<string> > grid(11000, std::vector<string>(50));
You probably also want to fix your IO loop, testing !in.eof() is usually wrong. Why not read a line at a time and split the line up, instead of reading single characters?
while (getline(in, c))
If all you need is to access all lines at once why you don't declare it as std::vector<std::string> and each line is an string??
std::string s;
std::vector<std::string> lines;
while( std::getline(in, s) ) lines.push_back( s );
std::cout << "File contain " << lines.size() << " line" << std::endl;
std::cout << "Char at [1][2] is " << lines[1][2] << std::endl; // assume [1][2] is valid!