Using cout to display an array in C++
10 hours ago, Mr_KoKa said:getline function reads line from stream into string so putting it in while loop like this, you keep overwriting the previous line with the next line from your text file. You're ending up with img containing last line of your text file.
To save every line in array you would need to enlarge the array after you read line. You could enlarge it by greater number then 1 so it wouldn't be enlarged every time you read new line, but it could take more memory then it needs to, you would then need to fit the array to elements count. So I will make example that will enlarge array one by one.
#include <iostream> #include <fstream> using namespace std; int main(){ ifstream File("cookies.asc"); string img; string *array = nullptr; int arraySize = 0; while(getline(File, img)){ string *newArray = new string[arraySize + 1]; for(int i = 0; i < arraySize; i++){ newArray[i] = array[i]; } newArray[arraySize] = img; arraySize++; delete[] array; array = newArray; } for(int i = 0; i < arraySize; i++){ cout << array[i] << std::endl; } delete[] array; }You can see that inside a loop I create newArray of size arraySize + 1, so it is one element larger then it was. Then I copy old array values into new array and at the last array position I set value of newly read line. Then I increment the arraySize to keep its new size, I delete old array and assign newArray pointer to array. After this array is enlarged and keeps line that has been read. After reading I iterate over array to print its elements, then I delete it to free memory.
I guess your assignment makes you to use arrays, but using stl containers would be easier and safer.
Thank you very much, and yes the assignment is making me use arrays.
7 hours ago, Unimportant said:And pray to God no exceptions are thrown.
This is not the way to do it, but as this seems a school assignment and the (artificial) limitations on what techniques may or may not be used are unclear it's hard to give a correct answer (normally, one would use std::vector, or at least use a smart pointer to cure the potential leaks).
Thankfully no exceptions where thrown. And you are right it is an assignment, an array was required. Probably a better way to do this but it worked so I'm happy.
Now i need to figure out how to save the edits to a new file. I think I have it but I don't know what exactly to save. You can see here what I tried.
cout << "Enter a file name to save." << '\n'; cin >> newname; ofstream OutFile(newname + type); OutFile << array << '\n';
Edit: Just figured it out.
Thanks guys.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now